Swift:是否有更简洁的方法来传递额外的UIBarButtonItem动作:选择器参数而不是使用button.tag?

时间:2016-02-20 04:25:31

标签: ios swift selector uibarbuttonitem

我目前正在开发类似于类似菜单的菜单,点击左右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 个答案:

答案 0 :(得分:1)

选项1: 在视图控制器中创建与每个UIBarButtonItem对应的两个属性。通过这种方式,您可以分辨哪一个被点击。

选项2: 子类UIBarButtonItem并添加您想要的属性。