iOS 使用输入框的inputAccessoryView属性实现键盘上添加视图

ShaylaWethe 7年前
   <p>在开发应用程序时会经常用到输入消息并发送消息的功能,比如今日头条或者UC头条这些软件底部都会有,如何想向这些应用一样点击UITextField或者UITextView就可以弹出键盘并在键盘上也能加上同意的输入和发送功能?</p>    <p>不少iOS同仁是通过监听触发键盘弹起和收起后的高度在相关位置添加输入消息和发送消息的视图或者改变视图的高度来实现的,这样比较麻烦,如何在不需监听键盘弹起和收起的情况下实现这样的功能?通过苹果自带的UITextField和UITextView的属性就可以实现如下图所示功能:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/2a9e9aa6a2f2a23f16ffd3e8e38931e4.gif"></p>    <p style="text-align:center">17.gif</p>    <p>UITextField和UITextView都有个辅助属性 inputAccessoryView ,通过它可以在键盘上添加视图,并实现先关功能,方法很简单,如下代码所示:</p>    <pre>  <code class="language-objectivec">import UIKit    class ViewController: UIViewController {      let kScreenWidth = UIScreen.main.bounds.size.width      let toolBar: UIToolbar = {          //创建ToolBar          let tmpToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 70))          tmpToolBar.backgroundColor = UIColor.gray          return tmpToolBar      }()      var textView: UITextView!        @IBOutlet weak var inputTextField: UITextField!      override func viewDidLoad() {          super.viewDidLoad()          //创建UITextView          textView = UITextView(frame: CGRect(x: 0, y: 5, width: kScreenWidth/4*3, height: 60))          textView.backgroundColor = UIColor.lightGray          let inputItem = UIBarButtonItem(customView: textView)          //创建发送按钮          let sendBtn = UIButton(frame: CGRect(x: 0, y: 5, width: kScreenWidth/4-40, height: 50))          sendBtn.contentMode = .center          sendBtn.setTitle("发送", for: .normal)          sendBtn.setTitleColor(UIColor.blue, for: .normal)          sendBtn.addTarget(self, action: #selector(handleSend(event:)), for: .touchUpInside)          let sendItem = UIBarButtonItem(customView: sendBtn)          //ToolBar添加textView和发送按钮          toolBar.items = [inputItem,sendItem]          //赋值给UITextField的inputAccessoryView          inputTextField.inputAccessoryView = toolBar      }      func handleSend(event: UIButton) -> () {          print(textView.text)          view.endEditing(true)      }  }</code></pre>    <p>是不是很简单。 open var inputAccessoryView: UIView? 可以看出,由于是继承UIView,所以可以放你想放的所以View和设置想设置的高度。</p>    <p>对 inputAccessoryView 感兴趣的同学,可以试下 inputView 会有惊喜的哦!</p>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/374cc6f94662</p>    <p> </p>