[英]how can I add a permanent character at the beginning of an input field in uiAlert Popup?
當用戶在我的應用程序中按下按鈕時,我會在其中顯示輸入文本字段的警報視圖。 我為此使用以下代碼:
func addTapped(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "", message: "Write a #name of a tag that you want to follow", preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .Default) { (_) in
if let field = alertController.textFields![0] as? UITextField {
if(field.text?.characters.count > 0) {
print("user put some data inside")
} else {
print("user did not put anything")
}
} else {
// user did not fill field
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }
alertController.addTextFieldWithConfigurationHandler { (textField) in
let attributedString = NSMutableAttributedString(string: "C-TAD-")
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(0,6))
textField.attributedText = attributedString
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
當用戶運行該應用程序時,他看到的效果很好:
但是里面的占位符文本是可移動的。 我想防止這種情況,並始終在此處顯示此文本,因此基本上將其鎖定在刪除選項上。
如何鎖定刪除首字母的可能性?
遵循媽媽的建議,我得以解決此問題。 我加了
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//This makes the new text black.
textField.typingAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
let protectedRange = NSMakeRange(0, 6)
let intersection = NSIntersectionRange(protectedRange, range)
if intersection.length > 0 {
return false
}
return true
}
方法,並在addTextFieldWithConfigurationHandler
設置文本字段的addTextFieldWithConfigurationHandler
-做到了:
UITextField具有可以自定義的leftView
和rightView
。 默認情況下,從不顯示leftView。 您可以將標簽添加為leftView或leftView的子視圖,並將左視圖設置為Always show。
試試這個代碼:
let leftLabel = UILabel(frame: CGRectMake(0,0,60,21))
leftLabel.text = "C-TAD-"
leftLabel.textColor = .lightGrayColor()
textField.leftView = leftLabel
textField.leftViewMode = .Always
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.