nunzio giulio caggegi nunzio giulio caggegi - 3 months ago 28
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
txtUsername.addSubview(imageViewUsername)


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

enter image description here

Answer

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

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)
}