我想通过闭包在视图控制器的属性中设置UIBarButtonItems数组。
因此,不要在viewDidLoad
中执行此操作:
let b1 = UIBarButtonItem(title: "MoveUp", style: .plain, target: self, action: #selector(b1Tapped(sender:)))
let b2 = UIBarButtonItem(title: "b2", style: .plain, target: self, action: #selector(b2Tapped(sender:)))
let b3 = UIBarButtonItem(title: "b3", style: .plain, target: self, action: #selector(b3Tapped(sender:)))
navigationItem.rightBarButtonItems = [b3, b2, b1]
我这样做:
lazy var bbItems: [UIBarButtonItem] = {
let b1 = UIBarButtonItem(title: "MoveUp", style: .plain, target: self, action: #selector(b1Tapped(sender:)))
let b2 = UIBarButtonItem(title: "b2", style: .plain, target: self, action: #selector(b2Tapped(sender:)))
let b3 = UIBarButtonItem(title: "b3", style: .plain, target: self, action: #selector(b3Tapped(sender:)))
return [b3, b2, b1]
}()
然后在
viewDidLoad
中:navigationItem.rightBarButtonItems = bbItems
我必须使其成为一个懒惰的var才能执行连接到按钮的功能。当它只是一个常规变量时,它没有执行。
这样做有什么缺点吗?有没有更好的办法?
谢谢
最佳答案
您可以通过参数将目标传递给闭包。我使用协议定义了抽象类型,该类型具有目标所需的功能。
很快就会像这样4
// it should be @objc because selectors need functions that are visibile to Objective-C
@objc protocol NavigaitonBarConfigurable: class {
func b1Tapped(_ sender: UIBarButtonItem)
func b2Tapped(_ sender: UIBarButtonItem)
func b3Tapped(_ sender: UIBarButtonItem)
}
/// create UIBarButtonItems
func createNavigationBarButtons(target: NavigaitonBarConfigurable) -> [UIBarButtonItem] {
let b1 = UIBarButtonItem(title: "MoveUp",
style: .plain,
target: target,
action: #selector(NavigaitonBarConfigurable.b1Tapped(_:)))
let b2 = UIBarButtonItem(title: "b2",
style: .plain,
target: target,
action: #selector(NavigaitonBarConfigurable.b2Tapped(_:)))
let b3 = UIBarButtonItem(title: "b3",
style: .plain,
target: target,
action: #selector(NavigaitonBarConfigurable.b3Tapped(_:)))
return [b1, b2, b3]
}
class ViewController: UIViewController {
// pass the function for creating buttons with target as self (self is NavigaitonBarConfigurable)
lazy var bbItems: [UIBarButtonItem] = createNavigationBarButtons(target: self)
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.setRightBarButtonItems(self.bbItems, animated: false)
}
}
extension ViewController: NavigaitonBarConfigurable {
func b1Tapped(_ sender: UIBarButtonItem) {
print("b1")
}
func b2Tapped(_ sender: UIBarButtonItem) {
print("b2")
}
func b3Tapped(_ sender: UIBarButtonItem) {
print("b3")
}
}
关于ios - 在ViewController中的属性关闭中定义UIBarButtonItems,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47311351/