NSNotification addObserver of keyboard event + UIButton 类型触发自动动画?

NSNotification addObserver of keyboard event + UIButton type triggers auto animation?

我试图在键盘显示后在键盘顶部垂直添加一个按钮。 问题是添加的按钮从左上角飞到我的目标位置,没有任何动画代码,当我做了以下两件事时:

  1. 我把UIKeyboardWillShowNotification的观察者添加到了NSNotification默认中心

    NSNotificationCenter.defaultCenter().addObserver(self, 选择器: "display:", 名称: UIKeyboardWillShowNotification, 对象: nil)

  2. 同时,我为 UIButton 设置了一个类型

    按钮 = UIButton(类型:.System)

或者,.Custom,等等。 如果我不做其中之一,自动胺化就根本不会发生。 当我使用 UISegmentedControl 时会发生同样的问题。 有什么想法吗?

代码: Swift 2.1 您可以单击文本框并触发键盘,然后您会看到一个按钮从左上角飞到键盘顶部。如果将 button = UIButton(type: .System) 替换为 button = UIButton(frame: frame),则不会发生。

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()  
  }  
}  

您可以通过在编辑文本字段时使用 UIToolBar 移除键盘来实现。 试试下面的代码,

 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()
}

不要忘记将 textField 委托与 UIController 连接起来以隐藏键盘。 我希望它会起作用。 :)