textField中的图标位置

时间:2016-08-29 13:10:33

标签: ios swift uiimageview uiimage uitextfield

我想在适当的快捷方式中使用这样的文本字段: enter image description here

我的代码是:

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)

我在文本字段的开头左侧完全移动了图标。它移动了吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

我测试过,它按预期工作,你可以看到我的代码: 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)
}

答案 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)