Chase
Chase

Reputation: 473

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!

Upvotes: 15

Views: 10275

Answers (4)

Brian
Brian

Reputation: 944

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
    }

}

Upvotes: 12

MikeNatty
MikeNatty

Reputation: 147

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

Upvotes: 4

Paludis
Paludis

Reputation: 734

I wanted to do the same thing, I ended up just overlaying a UITextField over the button and using the inputView of that instead.

Tip: set tintColor of the UITextField to UIColor.clearColor() to hide the cursor.

Upvotes: 3

Jason
Jason

Reputation: 650

You can create a view for the picker off screen view and move it on screen when you need it. Here's another post on this.

Upvotes: 0

Related Questions