Swift:除了使用 button.tag 之外,是否有更简洁的方法来传递额外的 UIBarButtonItem 操作:选择器参数?
Swift: Is there a cleaner way to pass an extra UIBarButtonItem action: Selector parameter other than using button.tag?
我目前正在开发一个类似 snapchat 的菜单,单击左右 UIBarButtonItem 会使屏幕向各自的方向移动。
TL;DR - 我想知道是否有一种(干净的)内置方式将标记作为可选类型传递以避免崩溃。
override func viewDidLoad() {
super.viewDidLoad()
// Other setup code here
let leftButton = UIBarButtonItem(title: leftButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
let rightButton = UIBarButtonItem(title: rightButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
// These tags are not a good solution because they aren't optionals!
leftButton.tag = 0
rightButton.tag = 1 // this isn't necessary, but I don't want it to crash...
// More setup here
}
func navButtonClicked(sender: UIBarButtonItem) {
// Goes right by default
let currentX = self.parentScrollView!.contentOffset.x
var screenDelta = self.parentScrollView!.frame.width
if sender.tag == 0 {
screenDelta *= -1
}
UIView.animateWithDuration(0.5, animations: {() in
self.parentScrollView!.contentOffset = CGPoint(x: currentX + screenDelta, y: 0)
})
}
我目前的解决方案有效,我只是在努力编写更简洁的代码。
谢谢!
选项 1:
在您的视图控制器中创建两个对应于每个 UIBarButtonItem 的属性。这样您就可以知道哪一个被点击了。
选项 2:
继承 UIBarButtonItem 并添加一个你想要的 属性。
我目前正在开发一个类似 snapchat 的菜单,单击左右 UIBarButtonItem 会使屏幕向各自的方向移动。
TL;DR - 我想知道是否有一种(干净的)内置方式将标记作为可选类型传递以避免崩溃。
override func viewDidLoad() {
super.viewDidLoad()
// Other setup code here
let leftButton = UIBarButtonItem(title: leftButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
let rightButton = UIBarButtonItem(title: rightButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
// These tags are not a good solution because they aren't optionals!
leftButton.tag = 0
rightButton.tag = 1 // this isn't necessary, but I don't want it to crash...
// More setup here
}
func navButtonClicked(sender: UIBarButtonItem) {
// Goes right by default
let currentX = self.parentScrollView!.contentOffset.x
var screenDelta = self.parentScrollView!.frame.width
if sender.tag == 0 {
screenDelta *= -1
}
UIView.animateWithDuration(0.5, animations: {() in
self.parentScrollView!.contentOffset = CGPoint(x: currentX + screenDelta, y: 0)
})
}
我目前的解决方案有效,我只是在努力编写更简洁的代码。
谢谢!
选项 1: 在您的视图控制器中创建两个对应于每个 UIBarButtonItem 的属性。这样您就可以知道哪一个被点击了。
选项 2: 继承 UIBarButtonItem 并添加一个你想要的 属性。