左侧的Swift文本字段添加图标

时间:2018-08-25 11:25:52

标签: ios swift

我正在尝试在文本字段中添加图标。在这里,我使用带有单独图标的多个文本字段,我需要创建子类来添加左侧图标。

下面是我的单个文本字段代码

var imageView = UIImageView();
var image = UIImage(named: "user-icon.png");
imageView.image = image;
imageView.frame = CGRectMake(100, 0, 20, 19);
usernameTextField.leftView = imageView;
usernameTextField.leftViewMode = UITextFieldViewMode.Always 

1 个答案:

答案 0 :(得分:1)

尝试此方法有效(快速4码)

extension UITextField{

    func setLeftImage(imageName:String) {

        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.image = UIImage(named: imageName)
        self.leftView = imageView;
        self.leftViewMode = .always
    }
}

像这样使用:

YourtextField.setLeftImage(imageName: "image_name")