34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftでキーボードにボタンを追加する

Posted at

Swift でキーボードにボタンを追加する方法です。
例では、フィールドを2つ Outlet 接続してあり、myField1 の編集時のキーボードの上部にDone ボタンを追加しています。Done ボタンをタップすると、myField2 の方に Success!! と表示してキーボードを消します。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var myField1: UITextField!   // 入力テキストフィールド
@IBOutlet weak var myField2: UITextField!   // メッセージ表示フィールド


override func viewDidLoad() {
    super.viewDidLoad()
   
    // ボタンビュー作成
    var myKeyboard = UIView(frame: CGRectMake(0, 0, 320, 40))
    myKeyboard.backgroundColor = UIColor.darkGrayColor()
    
    // Doneボタン作成
    var myButton = UIButton(frame: CGRectMake(5, 5, 80, 30))
    myButton.backgroundColor = UIColor.lightGrayColor()
    myButton.setTitle("Done", forState: UIControlState.Normal)
    myButton.addTarget(self, action: "onMyButton", forControlEvents: UIControlEvents.TouchUpInside)
    
    // ボタンをビューに追加
    myKeyboard.addSubview(myButton)
    
    // ビューをフィールドに設定
    myField1.inputAccessoryView = myKeyboard
    myField1.delegate = self
    
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// Done ボタンタップ時に実行するメソッド
func onMyButton () {
myField2.text = "Success!!"
self.view.endEditing(true )

}

// リターンキーでのデリゲートメソッド

func textFieldShouldReturn(textField: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
}

}`

iOS Simulator Screen Shot 2014.11.30 15.47.16.png
iOS Simulator Screen Shot 2014.11.30 15.47.38.png

34
32
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?