您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:標題欄與導航欄按鈕設定

編輯:iOS 開發綜合

在 iOS 中,導航欄標題可以不只是文字,也可以自訂按鈕,例如加入下拉箭頭,或用來切換選單。

加入左右按鈕與標題

self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearch)];
self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];

UIButton *titleButton = [[UIButton alloc] init];
[titleButton setTitle:@"首頁" forState:UIControlStateNormal];
[titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
titleButton.width = 100;
titleButton.height = 35;
self.navigationItem.titleView = titleButton;

自訂標題按鈕排版

若要讓圖片在右、文字在左,可建立 UIButton 子類別,重寫 imageRectForContentRect 與 titleRectForContentRect。

-(CGRect)imageRectForContentRect:(CGRect)contentRect {
    CGFloat imageW = self.height;
    CGFloat imageH = imageW;
    CGFloat imageX = self.width - imageW;
    return CGRectMake(imageX, 0, imageW, imageH);
}

-(CGRect)titleRectForContentRect:(CGRect)contentRect {
    CGFloat titleW = self.width - self.height;
    return CGRectMake(0, 0, titleW, self.height);
}

切換箭頭方向

-(void)titleButtonClick:(UIButton *)titleButton {
    UIImage *downImage = [UIImage imageWithName:@"navigationbar_arrow_down"];
    if (titleButton.currentImage == downImage) {
        [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    } else {
        [titleButton setImage:downImage forState:UIControlStateNormal];
    }
}

這種做法不需要額外狀態變數,也能避免魔法數字。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved