UIBarButtonItem在UIToolBar中无法单击

时间:2015-02-27 08:12:56

标签: ios swift uipickerview uibarbuttonitem uitoolbar

我有一个UIPickerView,我正在为其添加一个UIToolBarUIBarButtonItems

var toolBar = UIToolbar()
toolBar.frame.origin.y = -40
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()


var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePicker")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "canclePicker")

toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true

pickerView.addSubview(toolBar)
pickerView.bringSubviewToFront(toolBar)
view.bringSubviewToFront(toolBar)

问题是,当我尝试点击UIBarButtonItem时,它不会触发,它甚至不会识别它,它只是单击它下面的单元格。

enter image description here

2 个答案:

答案 0 :(得分:3)

你能试试这个代码。

    var textField = UITextField(frame: CGRectMake(20, 50, view.width - 40, 30))
    textField.backgroundColor = UIColor.redColor()
    view.addSubview(textField)

    var pickerView = UIPickerView(frame: CGRectMake(0, 200, view.width, 300))
    pickerView.backgroundColor = UIColor.whiteColor()
    pickerView.showsSelectionIndicator = true



    var toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()


    var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: "donePicker")
    var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "canclePicker")

    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    textField.inputView = pickerView
    textField.inputAccessoryView = toolBar

答案 1 :(得分:1)

我认为你需要使用标准的UIResponder机制来提升选择器和工具栏,或者使用隐藏的UITextField来获取相同的结果。

请参阅我对原始问题的最新回答:

Add buttons to UIPickerView - Swift 1.2