import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tfd: UITextField!
var upView :UIView = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
upView.frame = CGRectMake(0, self.view.frame.size.height , self.view.frame.size.width, 30.0)
upView.backgroundColor = UIColor.lightGrayColor()
// 创建“完成”button
let returnButton = UIButton(frame:CGRectMake(upView.bounds.size.width - 50, 0, 50, 30 ))
returnButton.backgroundColor = UIColor.lightGrayColor()
returnButton.setTitle("完成", forState: UIControlState.Normal)
returnButton.addTarget(self, action: "CancelBackKeyboard", forControlEvents: UIControlEvents.TouchDown)
upView.addSubview(returnButton)
self.view.addSubview(upView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleKeyboardDidShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleKeyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
println(upView)
}
func handleKeyboardDidShow(notification:NSNotification) {
var info:NSDictionary = notification.userInfo!
var kbSize = info.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue().size
var distanceToMove = kbSize!.height
self.adjustKeyboardHeight(distanceToMove)
}
func handleKeyboardWillHide(notification:NSNotification) {
upView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 30.0)
self.view.addSubview(upView)
}
func adjustKeyboardHeight(height:CGFloat) {
upView.frame = CGRectMake(0, self.view.frame.size.height - 30 - height, self.view.frame.size.width, 30.0)
self.view.addSubview(upView)
}
func CancelBackKeyboard() {
tfd.resignFirstResponder()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
tfd.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}