2015-05-28 81 views
1

電子郵件圖標和佔位符文本相互擁抱。如何設置在UITextField中添加的圖標的位置?

我想在它們之間添加一些空間。

enter image description here

下面是我使用創建這些字段的代碼。

// view for fields background 
var view = UIView(frame: CGRectMake(35, 300, 300, 90)); 
view.backgroundColor = UIColor.whiteColor(); 
view.layer.cornerRadius = 5.0 

// email text field 
var email = UITextField(frame: CGRectMake(0, 0, 300, 50)); 
email.backgroundColor = UIColor.whiteColor(); 

var emailIcon = UIImageView(); 

var emailIconImage = UIImage(named: "email_icon.png"); 

emailIcon.image = emailIconImage; 

email.leftView = emailIcon; 

email.leftViewMode = UITextFieldViewMode.Always 

email.layer.cornerRadius=5.0; 

email.attributedPlaceholder = NSAttributedString(string:"E-mail", 
    attributes:[NSForegroundColorAttributeName: UIColor.grayColor()]) 

emailIcon.frame = CGRect(x: 30, y: 15, width: 30, height: 20) 

view.addSubview(emailIcon) 

謝謝!

+0

的可能重複[插圖文字爲UITextField?] (http://stackoverflow.com/questions/2694411/text-inset-for-uitextfield) – Larme

回答

0

你可以從它的層改變位置:

txtemail.layer.position = CGPointMake(30, 30) 
0

子類的UITextField和實現以下方法放置在一個位置,你想要的佔位符文本 -

placeholderRectForBounds: 
4

做最簡單的方法這沒有子類是給EmailIcon寬度10pts比emailIconImage寬度多。然後根據你的need.Here在OBJ C中的代碼,希望你能弄清楚在迅速設置contentMode EmailIcon的居中或右

EmailIcon = [[UIImageView alloc] initWithImage: emailIconImage]; 
EmailIcon.frame = CGRectMake(0.0, 0.0, EmailIcon.image.size.width+10.0, EmailIcon.image.size.height); 
EmailIcon.contentMode = UIViewContentModeCenter; //Or UIViewContentModeRight 

textField.leftView = EmailIcon; 
textField.leftViewMode = UITextFieldViewModeAlways; 
+0

工程像魅力。 –

相關問題