1. 程式人生 > >UINavigationController 的 title 居中顯示 (UINavigationController 的 title 文字多時居中顯示)

UINavigationController 的 title 居中顯示 (UINavigationController 的 title 文字多時居中顯示)

一次偶然的機,我發現了,原來當 title 文字想對多時,是會靠左顯示而不是居中顯示,尷尬,處理起來也不是特別方便,可能你時間費了也解決不掉。這時候有些小朋友就說了,這太簡單了,我搞一個 label 賦給 titleview ,完了設定 label 文字居中就好了,如果有這樣想的朋友我希望你去試試,是不對滴,我這提供一種做法,供參考,如果能幫你解決問題,麻煩點贊鼓勵,謝謝

- (void)setDisplayCustomTitleText:(NSString*)text

{

    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake

(35, 0, SCREEN_WIDTH, 44)];

    titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

    titleView.autoresizesSubviews = YES;

    titleView.backgroundColor = [UIColorclearColor];

    UILabel *titleLabel = [[UILabel

alloc] initWithFrame:CGRectMake(35, 0, SCREEN_WIDTH, 44)];

    titleLabel.backgroundColor = [UIColor clearColor];

    titleLabel.textAlignment = NSTextAlignmentCenter;

    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    titleLabel.textColor = [UIColor

orangeColor];

    titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;

    titleLabel.autoresizingMask = titleView.autoresizingMask;

CGRect leftViewbounds = self.navigationItem.leftBarButtonItem.customView.bounds;

CGRect rightViewbounds = self.navigationItem.rightBarButtonItem.customView.bounds;

    CGRect frame;

    CGFloat maxWidth = leftViewbounds.size.width > rightViewbounds.size.width ? leftViewbounds.size.width : rightViewbounds.size.width;

    frame = titleLabel.frame;

    frame.size.width = SCREEN_WIDTH - maxWidth * 2;

    titleLabel.frame = frame;

    frame = titleView.frame;

    frame.size.width = SCREEN_WIDTH - maxWidth * 2;

    titleView.frame = frame;

    titleLabel.text = text;

    [titleView addSubview:titleLabel];

self.navigationItem.titleView = titleView;

}

錯誤的效果圖