ADS

2013年9月6日 星期五

2013.09.06, [Xcode] Change the navigation bar title size

Just some experience sharing.

給跟我有同樣困擾的人
如果navigation bar的title字數會變動的,
當字數長度達到一個地步會被截掉,
我們必須要resize調整字體大小才能show出一整行




    //Resize size of navigationbar title
    self.navigationItem.title = @"TESTTESTTEST";
    UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 300, 40)];
    tlabel.text=self.navigationItem.title;
    tlabel.textColor=[UIColor whiteColor];
    tlabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.3];
    tlabel.backgroundColor =[UIColor clearColor];
    tlabel.font = [UIFont boldSystemFontOfSize:20.0];
    tlabel.textAlignment = NSTextAlignmentCenter;
    tlabel.adjustsFontSizeToFitWidth=YES;
    self.navigationItem.titleView=tlabel;

Before:

After:


現在問題來了
如果我的leftButton和rightButton有時候沒出現,
因為titleView拿剩下的部份來做alignment,
儘管已經Center對齊,
還是會歪歪的,字數長也許沒關係,字數短看起來就歪掉了


我的解法是把螢幕切3等分,Label可以在title字數短時盡量把它往中間靠齊:
不過要先要環境的解析度(你是iphone還是ipad?)

    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGSize screenSize = CGSizeMake(screenBounds.size.width, screenBounds.size.height);
    
    self.navigationItem.title = @"TESTTESTTEST";
    //Resize size of navigationbar title
    UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake((screenSize.width/3),0, (screenSize.width/3), 40)];
    tlabel.text=self.navigationItem.title;
    tlabel.textColor=[UIColor whiteColor];
    tlabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.3];
    tlabel.backgroundColor =[UIColor clearColor];
    tlabel.font = [UIFont boldSystemFontOfSize:20.0];
    tlabel.textAlignment = NSTextAlignmentCenter;
    tlabel.adjustsFontSizeToFitWidth=YES;
    self.navigationItem.titleView=tlabel;

Before: (Ugly :-( )



After:


當然長字數依然要正常工作才行啦~




小小細節而已,若有錯誤煩請指教囉!~

p.s.我好像忘了做release tlabel的動作...? :P

Ref:
1. How to change font size of title in iphone?
2. Adjusting navigationItem.titleView's frame?

沒有留言: