我的代码是:
let imageViewUsername = UIImageView();
let imageUsername = UIImage(named: "icon_username.png");
imageViewUsername.image = imageUsername;
imageViewUsername.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
imageViewUsername.contentMode = UIViewContentMode.ScaleAspectFit
txtUsername.leftView = imageViewUsername;
txtUsername.leftViewMode = UITextFieldViewMode.Always
txtUsername.addSubview(imageViewUsername)
我在文本字段的开头左侧完全移动了图标。它移动了吗?
答案 0 :(得分:1)
override func viewDidLoad() {
super.viewDidLoad()
// Creating ImageView
let imageView = UIImageView()
// Downloading an image
imageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-person-128.png")!)!)
imageView.contentMode = .ScaleAspectFit
imageView.frame = CGRectMake(0, 0, 80, 100)
// Creating TextField
let textField = UITextField()
textField.placeholder = "Username"
textField.frame = CGRectMake(100, 100, 400, 100)
// Setting up TextField with ImageView
textField.leftView = imageView
textField.leftViewMode = .Always
// Showing the TextField on the ViewController's View
self.view.addSubview(textField)
}
答案 1 :(得分:0)
您可以根据需要移动X值,而不是X = 0。好像10-20会很好。 ,将WRT的高度和宽度更改为textfield。 更新的代码:
let imageViewUsername = UIImageView();
let imageUsername = UIImage(named: "icon_username.png");
imageViewUsername.image = imageUsername;
imageViewUsername.frame = CGRect(x: 10, y: 0, width: txtUsername.frame.height, height: txtUsername.frame.height) // Updated value.
imageViewUsername.contentMode = UIViewContentMode.ScaleAspectFit
txtUsername.addSubview(imageViewUsername)