2017-05-28 304 views
1

即時圖標試圖將圖標添加到我的用戶名文本框中,不知何故,我添加了圖標,但無法添加任何填充。將圖像添加到TextField

我的意思是,我希望它看起來像這樣: enter image description here

而我所得到的是這樣的: enter image description here

let usernameTextField: UITextField = { 
     let tf = UITextField() 


     let imageView = UIImageView() 

     let image = UIImage(named: "user-icon") 

     imageView.image = image 
     imageView.frame = CGRect(x: 0, y: 0, width: 10, height: 15) 
     tf.leftViewMode = UITextFieldViewMode.always 
     tf.leftView = imageView 
     tf.addSubview(imageView) 


     var placeholder = NSMutableAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.lightGray]) 
     tf.attributedPlaceholder = placeholder 
     tf.backgroundColor = UIColor.rgb(red: 34, green: 34, blue: 34) 
     tf.borderStyle = .roundedRect 
     tf.font = UIFont.systemFont(ofSize: 14) 
     tf.layer.cornerRadius = 25 
     tf.textColor = .white 
     tf.layer.borderWidth = 1 
     tf.layer.borderColor = UIColor(white: 1, alpha: 0.1).cgColor 
     tf.layer.masksToBounds = true 
     return tf 
    }() 

這是我的代碼塊。即使我改變x和y值,它也不會移動任何像素。

回答

2

增加視圖的寬度並居中圖像。相應地調整寬度(我已將其設置爲50)。試試這個...

let usernameTextField: UITextField = { 
     let tf = UITextField() 


     let imageView = UIImageView() 

     let image = UIImage(named: "user-icon") 

     imageView.image = image 
     imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 15) 
     imageView.contentMode = .scaleAspectFit 
     tf.leftViewMode = UITextFieldViewMode.always 
     tf.leftView = imageView 
     tf.addSubview(imageView) 


     var placeholder = NSMutableAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.lightGray]) 
     tf.attributedPlaceholder = placeholder 
     tf.backgroundColor = UIColor.init(red: 35.0/100.0, green: 34.0/100.0, blue: 34.0/100.0, alpha: 1) 
     tf.borderStyle = .roundedRect 
     tf.font = UIFont.systemFont(ofSize: 14) 
     tf.layer.cornerRadius = 25 
     tf.textColor = .white 
     tf.layer.borderWidth = 1 
     tf.layer.borderColor = UIColor(white: 1, alpha: 0.1).cgColor 
     tf.layer.masksToBounds = true 
     return tf 
    }() 
+0

首先我得到了RGB的擴展,所以我不需要使用/ 255。並沒有任何方法來提供一個特定的填充?剩下5px,右邊10px。因爲在另一種情況下,增加寬度可能對此時有用,所以我可能需要更多強大的工作人員。 – Alper

+0

啊好吧..不,沒有任何填充..另一種選擇是在左側和右側的圖像中添加透明區域。 – Bilal

+0

Uhm im在不同的問題上掙扎了好幾個小時,所以我的大腦現在不工作> _>你能給我一個關於添加透明區域的例子嗎 – Alper