Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I activate an inputView using a UIButton in Swift?

I am attempting to have a UIDatePicker come up as a keyboard when the user hits a UIButton. I was able to get it to work with a textfield, but I don't like how the cursor is visible and the user could enter in any text if they had an external keyboard. Here is my code:

@IBAction func dateFieldStart(sender: UITextField) {
        var datePickerStartView  : UIDatePicker = UIDatePicker()
        datePickerStartView.datePickerMode = UIDatePickerMode.Time
        sender.inputView = datePickerStartView    // error when sender is UIButton
}

I tried changing the sender to UIButton but it gave this error on the line that is marked above:

Cannot assign to 'inputView' in 'sender'

I have tried researching it and no one else seems to have had a problem with it. Anyone know how to trigger a UIDatePicker inputView using a UIButton or anything that might work better that the user cannot type into? Thanks!

like image 610
Chase Avatar asked Jul 11 '15 20:07

Chase


2 Answers

This is years after the original question, but for anyone who may be looking for solution to this you can subclass UIButton and provide a getter and setter for the inputView property. Be sure to call becomeFirstResponder in the setter and override canBecomeFirstResponder. For example:

class MyButton: UIButton {

    var myView: UIView? = UIView()
    var toolBarView: UIView? = UIView()
    
    override var inputView: UIView? {
        get {
            myView
        }
        
        set {
            myView = newValue
            becomeFirstResponder()
        }
    }

    override var inputAccessoryView: UIView? {
        get {
            toolBarView
        }
        set {
            toolBarView = newValue
        }
    }
    
    override var canBecomeFirstResponder: Bool {
       true
    }

}
like image 115
Brian Avatar answered Nov 15 '22 16:11

Brian


let tempInput = UITextField( frame:CGRect.zero )
tempInput.inputView = self.myPickerView       // Your picker
self.view.addSubview( tempInput )
tempInput.becomeFirstResponder()

It's a good idea to keep a reference to tempInput so you can clean-up on close

like image 36
MikeNatty Avatar answered Nov 15 '22 16:11

MikeNatty