【发布时间】:2021-10-08 08:32:37
【问题描述】:
我已经为 UITextField 添加了一个扩展,以显示带有颜色的底部边框,这是有效的。但是,我的意图是当用户点击文本字段以编辑文本时出现底部边框,并在完成编辑后消失边框。我已经提到了有关此问题的其他 stackoverflow 问题,但我找不到涉及底部边框和编辑时出现/消失的答案或问题。
extension UITextField {
func addBottomBorder() {
let bottomline = CALayer()
bottomline.frame = CGRect(x: 0,y:self.frame.size.height - 1, width: self.frame.size.width,height: 1)
bottomline.backgroundColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0, alpha: 1.0).cgColor
borderStyle = .none
self.layer.addSublayer(bottomline)
self.layer.masksToBounds = true
}
}
我对 swift 和 Ios 开发还很陌生。如果有人可以显示我应该添加到扩展文件中的内容以使边框在编辑时出现和消失,那将会很有帮助。
更新
视图控制器
func textFieldDidBeginEditing(_ textField: UITextField) {
movementTextField.addBottomBorder()
notesTextField.addBottomBorder()
descriptionTextField.addBottomBorder()
shotSize.addBottomBorder()
shotNameTextField.addBottomBorder()
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
movementTextField.removeBottomBorder()
notesTextField.removeBottomBorder()
descriptionTextField.removeBottomBorder()
shotSize.removeBottomBorder()
shotNameTextField.removeBottomBorder()
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
}
扩展更新
extension UITextField {
func addBottomBorder() {
let bottomline = CALayer()
bottomline.frame = CGRect(x: 0,y:self.frame.size.height - 1, width: self.frame.size.width,height: 1)
bottomline.backgroundColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0, alpha: 1.0).cgColor
borderStyle = .none
self.layer.addSublayer(bottomline)
self.layer.masksToBounds = true
}
func removeBottomBorder() {
let removebottomline = CALayer()
removebottomline.frame = CGRect(x: 0,y:self.frame.size.height - 1, width: self.frame.size.width,height: 1)
removebottomline.backgroundColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0, alpha: 1.0).cgColor
borderStyle = .none
self.layer.addSublayer(removebottomline)
self.layer.masksToBounds = true
}
}
【问题讨论】:
-
在textfield delgate函数didBeginEditing中可以出现边框,在edidEndEditing函数中可以消失边框。
-
@Kudos 嗨,你能用一些代码示例解释一下吗
标签: ios swift iphone uikit uitextfield