Reputation: 250
I was trying to add a button vertically on top of keyboard after the keyboard showed. The problem comes that the added button flies from top left corner to my target location, without any animation code, when I did the following two things:
I added the observer of UIKeyboardWillShowNotification to NSNotification default center.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "display:", name: UIKeyboardWillShowNotification, object: nil)
Meanwhile, I set up a type for UIButton like
button = UIButton(type: .System)
or, .Custom, whatever. If I didn't do one of them, the auto amination wouldn't happen at all. Same problem happens when I use a UISegmentedControl. Any idea?
The code:
Swift 2.1
You can click on the textbox and trigger the keyboard, then you will see a button flies from top left corner to top of keyboard. If you replace button = UIButton(type: .System)
with button = UIButton(frame: frame)
it wouldn't happen.
import UIKit
class ViewController: UIViewController {
var textfield: UITextField?
var button: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
textfield = UITextField(frame: CGRectMake(100, 100, 100, 50))
textfield!.layer.borderColor = UIColor.lightGrayColor().CGColor
textfield!.layer.borderWidth = 0.5
self.view.addSubview(textfield!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "display:", name: UIKeyboardWillShowNotification, object: nil)
}
func display(notification: NSNotification){
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
button = UIButton(type: .System)
button?.frame = CGRectMake(300, self.view.frame.height - keyboardSize.height - 40, 100, 40)
button?.setTitle("Button", forState: .Normal)
button?.addTarget(self, action: "remove:", forControlEvents: .TouchUpInside)
self.view.addSubview(button!)
}
}
func remove(var sender: UIButton?){
textfield?.resignFirstResponder()
sender?.removeFromSuperview()
sender = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Upvotes: 0
Views: 551
Reputation: 3237
You can do it by using UIToolBar to remove keyboard while editing textfield. Try below code,
override func viewDidLoad() {
super.viewDidLoad()
let keyboardDoneButtonView = UIToolbar()
keyboardDoneButtonView.sizeToFit()
keyboardDoneButtonView.items = NSArray(objects:
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "doneButton:"),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)) as? [UIBarButtonItem]
self.textField!.inputAccessoryView = keyboardDoneButtonView
}
func doneButton(sender:UIButton)
{
self.textField.resignFirstResponder()
}
Don't forget to wire up textField delegate with UIController to hide keyboard. I hope it will work. :)
Upvotes: 2