導航欄添加多個右按鈕且圖片在上文字在下

//自定義導航欄多個右按鈕

UIButton* myCollectionButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 35)];

[myCollectionButton setTitle:@"我的收藏" forState:UIControlStateNormal];

myCollectionButton.titleLabel.font = [UIFont systemFontOfSize:11];

[myCollectionButton addTarget:self action:@selector(myCollectionAction:) forControlEvents:UIControlEventTouchUpInside];

UIImageView* myCollectionImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"我的收藏"]];

myCollectionImage.frame = CGRectMake(myCollectionButton.frame.size.width / 4, 0, 20, 20);

[myCollectionButton addSubview:myCollectionImage];

//調用方法

[self initButton:myCollectionButton];

UIBarButtonItem* checkBar = [[UIBarButtonItem alloc] initWithCustomView:checkButton];

UIBarButtonItem* secrchBar = [[UIBarButtonItem alloc] initWithCustomView:secrchButton];

UIBarButtonItem* myCollectionBar = [[UIBarButtonItem alloc] initWithCustomView:myCollectionButton];

//添加多個按鈕(我只寫了一個按鈕,其余兩個按鈕相同設置)

self.navigationItem.rightBarButtonItems = @[secrchBar, myCollectionBar, checkBar];

self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

//使其按鈕 文字與圖片垂直顯示

- (void)initButton:(UIButton*)button {

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使圖片和文字水平居中顯示

button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;//使按鈕靠下顯示

[button setTitleEdgeInsets:UIEdgeInsetsMake(button.imageView.frame.size.height ,-button.imageView.frame.size.width, 0.0,0.0)];//文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度,距離下邊框和右邊框距離不變

[button setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,0.0, -button.titleLabel.bounds.size.width)];//圖片距離右邊框距離減少圖片的寬度,其它不邊

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容