Search code examples
iosuipickerviewresignfirstresponderuibuttonbaritem

UIBarButtonItem Action created in another class not firing (swift)


Ok so Im creating a UIPickerView programmatically to trigger from a UITextField inside a TableCell(this may be a stupid idea but lets go with it for now anyway).

I refactored all the code for it into its own class to declutter my UIViewControler:

class SeveritySection {
let pickerToolbar: UIToolbar!
let picker: UIPickerView!
let textField: UITextField!
let tableCell: UITableViewCell!

var pickerOptions = Array<String>()


init() {
    pickerToolbar  = UIToolbar()
    picker = UIPickerView()
    tableCell = UITableViewCell()
    textField = UITextField(frame: CGRectInset(tableCell.contentView.bounds, 15, 0))

}

func setOptions(optionsArray:Array<String>){

    pickerOptions = optionsArray;
}

/// Initalises the toolbar with done on the rhs for picker
/// :param: colour of the toolbar

func createPickerToolbarwith(#colour:UIColor){

    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: nil,action: Selector("doneButtonAction"))
    let toolbarButtons = [flexSpace, doneButton];

    pickerToolbar.sizeToFit()
    pickerToolbar.setItems(toolbarButtons, animated: true)
    pickerToolbar.backgroundColor = colour

}

func setupTextfield(){
    textField.placeholder = "Choose Severity"
    textField.inputView = picker
    textField.inputAccessoryView = pickerToolbar
    //        self.severityText.keyboardType = UIKeyboardType.NumberPad
    tableCell.addSubview(textField)

}

func setPickerDelegate(viewController: SinnerFormViewController){
    picker.delegate = viewController
    picker.dataSource = viewController

}

func setTextFieldTo(text:String){
    self.textField.text = text
}

func doneButtonAction() {
    textField.resignFirstResponder()
    println("Done pressed")

}

And so then I call in my UIViewController

var severitySection = SeveritySection()

self.severitySection.setPickerDelegate(self)
self.severitySection.createPickerToolbarwith(colour: UIColor.whiteColor())
self.severitySection.pickerToolbar.delegate = self
self.severitySection.setupTextfield()

but pressing the done button in the spinner toolbar won't fire any events. I tried setting the viewcontroller as the delegate to the UIToolbar, but that didnt change anything. I believe what I did was just refactor inline code in my view controller but I guess I missed something, or something implicitly defined is no longer there


Solution

  • Echoing what Huy Nghia mentioned in the comments, if you set the target to nil, you've effectively send a message to a nil object, which does nothing.

    [nil doneButtonAction] is effectively a no-op