在UITextField中显示右视图和清除按钮,可以通过以下步骤实现:
func textFieldDidBeginEditing(_ textField: UITextField) {
let clearButton = UIButton(type: .custom)
clearButton.setImage(UIImage(named: "clear_icon"), for: .normal)
clearButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
clearButton.addTarget(self, action: #selector(clearButtonTapped), for: .touchUpInside)
textField.rightView = clearButton
textField.rightViewMode = .whileEditing
}
在上面的代码中,我们创建了一个UIButton对象,并设置了其图像为我们自定义的清除图标。然后,我们将其添加到文本框的右视图中,并设置其模式为.whileEditing,这样它只会在文本框处于编辑状态时显示。
@objc func clearButtonTapped(_ sender: UIButton) {
textField.text = ""
}
在上面的代码中,我们定义了一个名为clearButtonTapped的方法,并在其中将文本框的文本设置为空字符串。这样,当用户点击清除按钮时,文本框中的文本将被清除。
通过以上步骤,我们可以在UITextField中显示右视图和清除按钮。
领取专属 10元无门槛券
手把手带您无忧上云