ios - 如何在 uiAlert Popup 中的输入字段的开头添加永久字符?

标签 ios swift uitextfield uitextfielddelegate

当用户按下我的应用程序中的按钮时,我向他显示带有输入文本字段的警报 View 。我使用以下代码:

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)

}

它运行良好,当用户运行他看到的应用程序时:

enter image description here

但是里面的占位符文本是可以删除的。我想防止这种情况发生,并始终在此处显示此文本,因此基本上锁定其上的删除选项。

如何锁定删除这些前几个字母的可能性?

最佳答案

UITextField 有一个可以自定义的 leftViewrightView。默认情况下,leftView 永远不会显示。您可以添加标签作为 leftView 或 leftView 的 subview ,并将左 View 设置为始终显示。

试试这个代码:

    let leftLabel = UILabel(frame: CGRectMake(0,0,60,21))
    leftLabel.text = "C-TAD-"
    leftLabel.textColor = .lightGrayColor()

    textField.leftView = leftLabel
    textField.leftViewMode = .Always

关于ios - 如何在 uiAlert Popup 中的输入字段的开头添加永久字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39515133/

相关文章:

ios - 无 url 编码的 Moya Alamofire 请求

ios - 如何将UITextView的光标移动到TOUCHED LOCATION?

ios - `flatMap` 发布者出现不同的错误

ios - 如何将UITextField限制为仅英语? (停止中文拼音输入)

objective-c - 如何在 UITextField 中键入文本时更新 UILabel

html - 在 Swift 中访问 HTML 表格数据

ios - 如何使用高度计? (增减法)

ios - 检查 viewDidLoad 上的 UITextField 是否为空并启用按钮

ios - UICollectionView View 和约束以使单元格适合

ios - NavigationBar 宽度在页面 View Controller 中随机加倍