3
2

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.

UITextField内に画像などを表示させる (.leftView、.rightView)

Posted at

#今回の内容
205FB713-620C-4939-B425-B8B65B86563C_1_105_c.jpeg

#コードと簡単解説

  • .leftViewMode.alwaysで設定しているので常に.leftViewが表示されます。(.rightViewでも同様です)

  • .leftView.rightViewUIViewを設定しなければなりませんが、UIImageViewUISwitchなどの様にUIViewが階層に含まれていれば設定できる様です。(全て調べられた訳では無いので設定出来ない場合もあるかも知れません)

import UIKit

class FirstActionViewController: UIViewController {
    
    @IBOutlet weak var textfield: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textfield.leftViewMode = .always
        textfield.leftView = {() -> UIImageView in
            
            let imageView = UIImageView(frame: CGRect(x: textfield.frame.minX + 10, y: textfield.frame.minY, width: textfield.frame.height - 10, height: textfield.frame.height))
            imageView.image = UIImage(systemName: "lock.fill")
            imageView.tintColor = .systemRed
            
            return imageView
        }()
        

        //コードで作成したUITextField
        let textfield01 = UITextField()
        textfield01.frame = CGRect(x: view.frame.maxX / 10, y: view.frame.maxY / 6, width: view.frame.width - (view.frame.maxX / 5), height: 50)
        textfield01.placeholder = "UITextField01"
        textfield01.layer.cornerRadius = 10.0
        textfield01.layer.borderWidth = 1.0
        textfield01.leftView = {() -> UIImageView in
            
            let imageView = UIImageView(frame: CGRect(x: textfield01.frame.minX, y: textfield01.frame.minY, width: textfield01.frame.height, height: textfield01.frame.height))
            imageView.image = UIImage(systemName: "lock.fill")
            imageView.tintColor = .systemRed
            
            return imageView
         }()
        
        textfield01.rightViewMode = .always
        textfield01.rightView = UISwitch()
        textfield01.leftViewMode = .always
        textfield01.layer.borderColor = UIColor.black.cgColor
        textfield01.backgroundColor = .white
        view.addSubview(textfield01)   
    }
       
}

終わり

ご指摘、ご質問などありましたら、コメントまでお願い致します。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?