在swift中禁用UITextfield的用户输入

问题描述 投票:42回答:7

我知道,这是一个非常微不足道的问题。但我在网上找不到任何东西。

我需要禁止用户编辑文本字段内的文本。这样当单击文本时,键盘就不会显示出来。

有任何想法吗?

一个程序化的解决方案,或者如果可以通过故事板,那将是很棒的。

ios swift uitextfield editing
7个回答
87
投票

试试这个:

Swift 2.0:

textField.userInteractionEnabled = false

Swift 3.0:

textField.isUserInteractionEnabled = false

或者在故事板中取消选中“启用用户交互”


39
投票

另一个解决方案,将您的控制器声明为UITextFieldDelegate,实现此回调:

@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    myTextField.delegate = self
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    if textField == myTextField {
        return false; //do not show keyboard nor cursor
    }
    return true
}

21
投票

在故事板中,您有两个选择:

  1. 将控件的'enable'设置为false。

  1. 将视图的“用户交互启用”设置为false

这些选择之间的区别是:

要在屏幕中显示的文本字段的外观。

  1. 首先设置控件启用。您可以看到背景颜色已更改。
  2. 其次是设置视图“启用用户交互”。背景颜色不会改变。

在代码中:

  1. textfield.enable = false
  2. textfield.userInteractionEnabled = NO 针对Swift 3进行了更新 textField.isEnabled = false textfield.isUserInteractionEnabled = false

2
投票

我喜欢像过去那样做。您只需使用这样的自定义UITextField类:

//
//  ReadOnlyTextField.swift
//  MediFormulas
//
//  Created by Oscar Rodriguez on 6/21/17.
//  Copyright © 2017 Nica Code. All rights reserved.
//

import UIKit

class ReadOnlyTextField: UITextField {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override init(frame: CGRect) {
        super.init(frame: frame)

        // Avoid keyboard to show up
        self.inputView = UIView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Avoid keyboard to show up
        self.inputView = UIView()
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // Avoid cut and paste option show up
        if (action == #selector(self.cut(_:))) {
            return false
        } else if (action == #selector(self.paste(_:))) {
            return false
        }

        return super.canPerformAction(action, withSender: sender)
    }

}

0
投票

如果您不希望用户能够修改UILabel中的任何内容,您可以使用UITextField

一个程序化的解决方案是使用enabled属性:

yourTextField.enabled = false

在故事板中执行此操作的方法:

取消选中UITextField属性中的Enabled复选框


0
投票

Swift 4.2 / Xcode 10.1:

只需取消选中在故事板中启用的行为 - >属性检查器。


0
投票

您应该使用“isEditable”而不是“userInteractionEnabled”,因为如果UITextfield为更多行,那么您看到的那个就可以滚动。 “userInteractionEnabled”不适用于滚动。

斯威夫特4

textView.isEditable = false
© www.soinside.com 2019 - 2024. All rights reserved.