4
4

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 3 years have passed since last update.

TextFieldの内部に×ボタンを配置する

Posted at

##完成系
スクリーンショット 2020-09-08 18.54.37.png
##やり方
TextFieldにはrightViewというプロパティがあるのでそこにボタンをセットしてあげます。
ただ、rightViewに直接ボタンを配置すると大きさを指定しても拡大されてしまうので、あいだにUIViewを挟みます。

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        //ボタンのY座標は(TextFieldの高さ-ボタンの高さ)/2
        let button = UIButton(frame: CGRect(x: 5, y: 5, width: 20, height: 20))
        button.contentEdgeInsets = .init(top: 0, left: 0, bottom: 3, right: 0)
        button.setTitle("×", for: .normal)
        button.backgroundColor = .lightGray
        button.layer.cornerRadius = button.frame.width / 2
        //ボタンに処理を追加
        button.addTarget(self, action: #selector(tappedButton), for: .touchUpInside)
        view.addSubview(button)
        //デフォルトだと表示されていない
        textField.rightViewMode = .always
        textField.rightView = view
    }

    //タップされたときの処理
    @objc func tappedButton() {
        print("tapped")
    }

}
4
4
0

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?