简体   繁体   中英

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!

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
    }

}
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

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.

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.

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