【问题标题】:Hide selection handles in UITextField在 UITextField 中隐藏选择句柄
【发布时间】:2014-05-17 03:23:57
【问题描述】:

我有一个UITextField,它插入一些文本并立即选择所有文本,因此用户可以单击关闭并接受预填充的数据或键入其他任何内容并覆盖所有内容。我称之为这样做:

[myTextField setSelectedTextRange:[myTextField textRangeFromPosition:myTextField.beginningOfDocument toPosition:myTextField.endOfDocument]];

我想知道是否有隐藏选择文本附带的手柄(圆形手柄,一个左上角,一个右下角),因为它不符合我们的 UI 设计,并且没有他们的目的。

【问题讨论】:

    标签: ios objective-c text uitextfield selection


    【解决方案1】:

    这是一个简单的 Swift 3 解决方案,非常适合我。

    class ViewController: UIViewController, UITextFieldDelegate {
        @IBOutlet weak var textField: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            textField.delegate = self
            textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        }
    
        // When editing starts, select all and then make handles (and cursor) invisible
        public func textFieldDidBeginEditing(_ textField: UITextField) {
            DispatchQueue.main.async {
                textField.selectAll(nil)
                textField.tintColor = .clear
            }
        }
    
        // If user types, restore cursor visibility  
        func textFieldDidChange(_ textField: UITextField) {
            DispatchQueue.main.async {
                textField.tintColor = .blue
            }
        }
    }
    

    注意 1:我最初并没有将更改分派到主队列,但我观察到更改有时无法正确呈现。将调度添加到主队列后,我再也没有看到这种行为。

    注意 2:我真的很想使用 UITextFieldDelegate 的 shouldChangeCharactersIn 处理程序使光标再次可见,但由于某种原因,当用户在 textField 中键入时,该方法从未被调用。所以我改用了 .editingChanged 事件,这似乎工作得很好,但不是很干净恕我直言。如果有人知道为什么以下内容不能作为 UITextFieldDelegate 的一部分工作,请发表评论。谢谢!

    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            textField.tintColor = .blue
            return true
        }
    

    【讨论】:

      【解决方案2】:

      如果只是为了外观,你可以继承 UITextField 并覆盖:

      - (void)setSelectedTextRange:(UITextRange *)selectedTextRange {
      //
      [super setSelectedTextRange:selectedTextRange];
      
      self.tintColor = selectedTextRange.empty ? <default cursor color> : [UIColor clearColor];}
      

      手柄还在,只是不可见。

      【讨论】:

        【解决方案3】:

        我不相信在UITextField/UITextView 中有本地方法可以做到这一点。您可能不得不使用CoreText 从头开始​​构建一些东西。

        也就是说,为了可用性,将它们保留在那里可能是个好主意?

        或者,您可以通过将NSBackgroundColorAttributeName 添加到AttributedText 并在用户按下退格键时以编程方式将其清除来“伪造”它?

        【讨论】:

        • 文本字段只有 2-3 个数字,因此在这种特定情况下,句柄会造成更大的伤害而不是帮助。我确实认为 NSBackgroundColorAttributeName 是一个很好的解决方案,所以谢谢!
        • 2018 年您好 - 现在有更好的解决方案吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        相关资源
        最近更新 更多