程式大概就這樣
沒太多需解釋的地方
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
emailTxt.keyboardType = .emailAddress
emailTxt.clearButtonMode = .whileEditing
numTxt.keyboardType = .numberPad
self.addDoneButtonOnKeyboard()
}
//在鍵盤上 新增按鈕
func addDoneButtonOnKeyboard() {
//btn1.setImage(UIImage(named: "tab-album"), forState: .plan)
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
doneToolbar.barStyle = UIBarStyle.default
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
//文字按鈕
let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "確定", style: UIBarButtonItemStyle.done, target: self, action: #selector(doneButtonAction))
//圖片按鈕
let gogoBtn: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "tab-album"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(gogoButtonAction))
var items = [UIBarButtonItem]()
items.append(gogoBtn) //左邊按鈕
items.append(flexSpace)
items.append(doneBtn) //右邊按鈕
doneToolbar.items = items
doneToolbar.sizeToFit()
//指定哪個 text 欄位
self.emailTxt.inputAccessoryView = doneToolbar
}
func gogoButtonAction() {
print("gogo.....")
//do something ...
}
func doneButtonAction() {
self.emailTxt.resignFirstResponder()
print("done.....")
//do something ...
}
完整的 swift project:
https://github.com/hellofire/swift_keyboard
其他參考資料
這兒有篇文章 教你設計一個全新的鍵盤 (輸入法)
iOS 8: Creating a Custom Keyboard in Swift
這個套件 解決鍵盤擋到畫面上的欄位的問題
IQKeyboardManager - GitHub
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more.
常常跳出鍵盤時,擋住了畫面中的欄位,看看這幾篇文章如何解決:
Move View Behind Keyboard in iOS8 With Swift
How do I scroll the UIScrollView when the keyboard appears? --stackover flow
How to make UITextField move up when keyboard is present
--
iOS 8 - How to hide suggestion list above keyboard?