我目前正在研究一个类似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:Sublass UIBarButtonItem 并添加所需的属性。