当用户按下我的应用程序中的按钮时,我会向他显示带有输入文本字段的警报视图。我使用以下代码:
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)
}
当用户运行他看到的应用程序时,它运行良好:
但内部的占位符文本是可移除的。我想阻止它并且总是在那里显示这个文本,所以基本上锁定它上面的删除选项。
如何锁定删除首字母的可能性?
答案 0 :(得分:0)
根据maddy的建议,我能够解决这个问题。我添加了
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
中文本字段的委托 - 这就是诀窍:)
答案 1 :(得分:0)
UITextField可以自定义 leftView
和 rightView
。默认情况下,从不显示leftView。您可以添加标签作为leftView或作为leftView的子视图,并将左视图设置为始终显示。
试试这段代码:
let leftLabel = UILabel(frame: CGRectMake(0,0,60,21))
leftLabel.text = "C-TAD-"
leftLabel.textColor = .lightGrayColor()
textField.leftView = leftLabel
textField.leftViewMode = .Always