iOS中navigationItem的titleView如何置中

來源:互聯網
上載者:User

標籤:

開發過程中,發現titleview很難置中,通過各種嘗試終於找到瞭解決方法。

首先清楚你個概念:

  1. leftBarButtonItem,導航條中左側button。

  2. rightBarButtonItem,導航條中右側button。

  3. titleview,不用介紹了吧,就是標題。

問題原因:

經過嘗試,發現titleview的起點位置和尺寸依賴於leftBarButtonItem和rightBarButtonItem的位置。

解決方案:

設定titleview之前,先初始化leftBarButtonItem和rightBarButtonItem的位置,然後根據leftBarButtonItem和rightBarButtonItem的位置來使titleview置中。

//以下使參考代碼。//必須放在 leftBarButtonItem和rightBarButtonItem初始化之後調用- (void)setDisplayCustomTitleText:(NSString*)text{    // Init views with rects with height and y pos    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];    // Use autoresizing to restrict the bounds to the area that the titleview allows    titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;    titleView.autoresizesSubviews = YES;    titleView.backgroundColor = [UIColorclearColor];    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];    titleLabel.tag = kUIVIEWCONTROLLER_LABEL_TAG;    titleLabel.backgroundColor = [UIColor clearColor];    titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];    titleLabel.textAlignment = UITextAlignmentCenter;    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;    titleLabel.textColor = TC_CNavigationTitleColor;    titleLabel.lineBreakMode = UILineBreakModeClip;    titleLabel.textAlignment = UITextAlignmentCenter;    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;    maxWidth += 15;//leftview 左右都有間隙,左邊是5像素,右邊是8像素,加2個像素的閥值 5 + 8 + 2    frame = titleLabel.frame;    frame.size.width = 320 - maxWidth * 2;    titleLabel.frame = frame;    frame = titleView.frame;    frame.size.width = 320 - maxWidth * 2;    titleView.frame = frame;    // Set the text    titleLabel.text = text;        // Add as the nav bar‘s titleview    [titleView addSubview:titleLabel];    self.navigationItem.titleView = titleView;}

 

iOS中navigationItem的titleView如何置中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.