简体   繁体   中英

UIBarButtonItem not clickable in UIToolBar

I have a UIPickerView and I am adding a UIToolBar with 2 UIBarButtonItems to it.

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)

The problem is, that when I try to click on the the UIBarButtonItem, it doesn't fire, it doesn't even recognize it, it just clicks the cell beneath it.

在此处输入图片说明

Can you try this codes.

    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

I believe that you need to raise the picker and toolbar using the standard UIResponder mechanism or cheat by using a hidden UITextField to get the same result.

See my updated answer to your original question:

Add buttons to UIPickerView - Swift 1.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM