Add image to UITextField in Xcode?

后端 未结 9 1030
时光取名叫无心
时光取名叫无心 2020-12-23 08:41

\"enter

I need to implement the concept of dropdown in Xcode.

For

9条回答
  •  感动是毒
    2020-12-23 09:19

    Step 1: Add this class to your project and add it to your textFiled's class in identity inspector,

    class MyCustomTextField: UITextField {
    
        @IBInspectable var inset: CGFloat = 0
    
        @IBInspectable var leftImage: String = String(){
            didSet{
                leftViewMode = UITextFieldViewMode.Always
                leftView = UIImageView(image: UIImage(named: leftImage))
            }
        }
    
        override func textRectForBounds(bounds: CGRect) -> CGRect {
            return CGRectInset(bounds, inset, inset)
        }
    
        override func editingRectForBounds(bounds: CGRect) -> CGRect {
            return textRectForBounds(bounds)
        }
    
        override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
            return CGRectInset(CGRectMake(0, 2, 40, 40), 10, 10) //Change frame according to your needs
        }
    }
    

    Step 2: Set text insets and left image from interface builder.

    Step 3: Enjoy.

提交回复
热议问题