ios - 禁用文本字段触摸但仍接受编辑?

标签 ios objective-c swift uitextfield

我的问题与this one相反.

我有多个文本字段,我将一个文本字段默认设置为第一响应者,但我不希望他们点击不同的 TextView 并手动转到它们。我仍然希望文本字段是可编辑的。有没有办法禁止用户触摸文本字段进行编辑?

最佳答案

创建一个UITextField子类并覆盖hitTest point方法并返回nil

class CustomTextField: UITextField {
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        return nil
    }
}

在 View Controller 中使用自定义类。在 viewDidAppear 中,在第一个文本字段中使用 becomeFirstResponder,在 textFieldShouldReturn 方法中移动到下一个文本字段。确保将委托(delegate)设置为所有文本字段。

class ViewController: UIViewController, UITextFieldDelegate {

    let textField1 = CustomTextField()
    let textField2 = CustomTextField()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        textField1.delegate = self
        textField1.returnKeyType = .next
        view.addSubview(textField1)

        textField2.delegate = self
        textField2.returnKeyType = .send
        view.addSubview(textField2)

        //add constraints or set frame
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textField1.becomeFirstResponder()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == textField1 {
            textField2.becomeFirstResponder()
        }
        return true
    }
}

关于ios - 禁用文本字段触摸但仍接受编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56156228/

相关文章:

ios - 为什么我可以直接在我的设备上安装应用程序商店分发版本?

ios - 仅限 UIScrollView AutoLayout 垂直

ios - 按钮不会取消隐藏

ios - Apple Mach -O Linker 命令失败

ios - 从 Objective-C iOS 中的 View Controller 在应用程序委托(delegate)数组中添加对象

ios - Sprite 套件物理 : possible to use a fixed update?

ios - 在 Objective-C 中,如何在不舍入的情况下删除 float 的尾随零?

ios - 将数据从 TableView 传递到详细 View 时未更新详细 View

ios - 使用错误的 Localized.string

swift - 使用 SKStoreProductViewController 或 SKStoreReviewController 进行应用评级/评论?