我知道,这是一个非常微不足道的问题。但我在网上找不到任何东西。
我需要禁止用户编辑文本字段内的文本。这样当单击文本时,键盘就不会显示出来。
有任何想法吗?
一个程序化的解决方案,或者如果可以通过故事板,那将是很棒的。
试试这个:
Swift 2.0:
textField.userInteractionEnabled = false
Swift 3.0:
textField.isUserInteractionEnabled = false
或者在故事板中取消选中“启用用户交互”
另一个解决方案,将您的控制器声明为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
}
在故事板中,您有两个选择:
这些选择之间的区别是:
要在屏幕中显示的文本字段的外观。
在代码中:
textfield.enable = false
textfield.userInteractionEnabled = NO
针对Swift 3进行了更新
textField.isEnabled = false
textfield.isUserInteractionEnabled = false
我喜欢像过去那样做。您只需使用这样的自定义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)
}
}
如果您不希望用户能够修改UILabel
中的任何内容,您可以使用UITextField
一个程序化的解决方案是使用enabled
属性:
yourTextField.enabled = false
在故事板中执行此操作的方法:
取消选中UITextField
属性中的Enabled复选框
Swift 4.2 / Xcode 10.1:
只需取消选中在故事板中启用的行为 - >属性检查器。
您应该使用“isEditable”而不是“userInteractionEnabled”,因为如果UITextfield为更多行,那么您看到的那个就可以滚动。 “userInteractionEnabled”不适用于滚动。
斯威夫特4
textView.isEditable = false