问题描述
当我单击TextField时,当创建UITexfield的子类以隐藏复制/粘贴等按钮时,我面临一个问题。这是该类的代码:
class UITextFieldCustom: UITextField {
var enableLongPressActions = false
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!}
override init(frame: CGRect) {
super.init(frame: frame)}
override func canPerformAction(_ action: Selector,withSender sender: Any?) -> Bool {
return enableLongPressActions
}
}
当我从情节提要中将其用于texfield时,代码运行良好,但是当将textField设置为编程方式时,我会收到以下消息:线程1:信号SIGABRT
这是我的View Controller扩展中部分代码中的textField声明:
extension MenuViewController {
func tabBarCentre(nameTextField: UITextFieldCustom) {
let titleLeftbutton = UIButton(type: .system)
titleLeftbutton.tintColor = #colorLiteral(red: 0.370555222,green: 0.3705646992,blue: 0.3705595732,alpha: 1)
let leftButtonConfig = UIImage.SymbolConfiguration(
pointSize: 20,weight: .bold,scale: .small)
let leftButtonImage = UIImage(
systemName: "chevron.left",withConfiguration: leftButtonConfig)
titleLeftbutton.setimage(leftButtonImage,for: .normal)
titleLeftbutton.addTarget(self,action: #selector(dateMoinsUn),for: .touchUpInside)
// Création du text central qui recevra le DatePicker
nameTextField.frame = CGRect(x: 0,y: 0,width: 70,height: 25)
nameTextField.backgroundColor = #colorLiteral(red: 0.9685223699,green: 0.9686879516,blue: 0.9685119987,alpha: 1)
nameTextField.placeholder = "Ajouter date"
nameTextField.font = nameTextField.font?.withSize(15)
nameTextField.font = UIFont.preferredFont(forTextStyle: .headline)
nameTextField.textAlignment = .center
错误消息在我的viewController中:
class MenuViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tabBarCentre(nameTextField: titleNavBarTextField) // THE ERROR IS HERE !!!!
self.titleNavBarTextField.setInputViewDatePicker(target: self,textField: titleNavBarTextField,selector1: #selector(tapped),selector2: #selector(todaypressed))
titleNavBarTextField.text = displayToday()
}
}
谢谢。
解决方法
将此方法添加到代码中,然后查看更改。您还可以自定义对文本字段的处理方式。如果要禁用所有文本字段操作,则只需在func canPerformAction方法中“返回false”即可。
override func caretRect(for position: UITextPosition) -> CGRect {
return CGRect.zero
}
override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
return []
}
override func canPerformAction(_ action: Selector,withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.cut(_:)) || action == #selector(UIResponderStandardEditActions.selectAll(_:)) || action == #selector(UIResponderStandardEditActions.paste(_:)) {
return false
}
// Default
return super.canPerformAction(action,withSender: sender)**