首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UINavigationItem 右側多個按鈕:用自訂 UIView 容器

     編輯:程式設計綜合問答

需求

導航列右側已有一個按鈕,需再加一個並排顯示。

解決方案:自訂 UIView 包含多個 UIButton

UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];

UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame = CGRectMake(0, 2, 30, 40);
[btn1 setImage:[UIImage imageNamed:@"icon1"] forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:btn1];

UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
btn2.frame = CGRectMake(70, 2, 30, 40);
[btn2 setImage:[UIImage imageNamed:@"icon2"] forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(action2) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:btn2];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:container];

Swift 版本

let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
let btn1 = UIButton(type: .custom)
btn1.frame = CGRect(x: 0, y: 2, width: 30, height: 40)
btn1.setImage(UIImage(named: "icon1"), for: .normal)
btn1.addTarget(self, action: #selector(action1), for: .touchUpInside)
container.addSubview(btn1)

let btn2 = UIButton(type: .custom)
btn2.frame = CGRect(x: 70, y: 2, width: 30, height: 40)
btn2.setImage(UIImage(named: "icon2"), for: .normal)
btn2.addTarget(self, action: #selector(action2), for: .touchUpInside)
container.addSubview(btn2)

navigationItem.rightBarButtonItem = UIBarButtonItem(customView: container)

替代方案:iOS 11+ 陣列屬性

// 僅支援系統樣式按鈕 (UIBarButtonItem),不支援自訂 View
self.navigationItem.rightBarButtonItems = @[item1, item2, item3];

若需自訂圖片/尺寸,仍需用容器 View 方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved