我构建了一个静态的tableview,其行数比屏幕多,因此用户必须滚动查看所有单元格。
每个单元格都有一个文本字段,该字段具有以下类以添加下边框:
class TextFieldWithBottomBorder: UITextField {
let border = CALayer()
let width = CGFloat(1.0)
func addBottomBorder(color: UIColor){
self.border.borderColor = color.cgColor
self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height:self.frame.size.height)
self.border.borderWidth = self.width
self.layer.addSublayer(self.border)
self.layer.masksToBounds = true
}
func changeBorderColor(color: UIColor){
self.border.borderColor = color.cgColor
}
}
我在从服务器接收到一些数据后调用这个方法。
self.firstnameTextField.text = firstNameFromDB
self.firstnameTextField.addBottomBorder(color: .blue)
这对当前显示的每个单元格都适用。但不在当前视图中的with单元格比文本字段短。
看这个截图,对于“Vorname”,意思是firstName一切看起来都很好,但是对于email,password等,边界要短。
http://share-your-photo.com/34b5e80253
最佳答案
在调用addBottomBorder之后,UITextField的大小似乎正在调整,因此该行使用的UIView现在不够宽。很难说为什么在没有看到更多代码的情况下会出现这种情况,但是有几种方法可以用来克服它。
1)切换到UIView而不是CALayer,并使用auto layout将视图保持在校正位置。
2)重写layoutSubviews以更新底线框架。
对您来说最简单的可能是选项2(尽管我会选择选项1),它看起来是这样的:
override func layoutSubviews() {
super.layoutSubviews()
self.border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height:self.frame.size.height)
}
现在,只要文本字段的帧/大小更改,边框线CALayer的帧/大小就会相应地更新。
关于ios - TableView中Swift TextField的底部边框宽度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44385229/