Reputation: 852
I would like a textfield with in an appropriate shortcut like this:
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?
Upvotes: 0
Views: 419
Reputation: 9136
I tested and it is working as expected, you can see my code:
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)
}
Upvotes: 1
Reputation: 879
Instead of X=0 , you can move the X values as per your requirement. as if 10-20 will be good. , Change the height and width WRT to textfield. Updated code:
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)
Upvotes: 0