nunzio giulio caggegi nunzio giulio caggegi - 1 year ago 148
Swift Question

Icon position in textField

I would like a textfield with in an appropriate shortcut like this:
enter image description here

my code is this:

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

I get completely moved icon to the left, at the beginning of the textfield. as it moves?

enter image description here

Answer Source

I tested and it is working as expected, you can see my code: enter image description here

override func viewDidLoad() {

  // Creating ImageView
  let imageView = UIImageView()
  // Downloading an image
  imageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "")!)!)
  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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download