[英]Bottom Border Width on Swift TextField in TableView
我建立了一個靜態tableview,其中Rowes的數量超過了屏幕,因此用戶必須滾動才能看到所有單元格。
每個單元格都有一個帶有以下類的文本字段,以添加底部邊框:
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)
這對於當前顯示的每個單元格都適用。 但是當前視圖中帶有的單元格比文本字段短。 看到此屏幕快照,“ Vorname”表示“ FirstName”一切看起來不錯,但對於電子郵件,密碼等,邊框較短。 http://share-your-photo.com/34b5e80253
調用addBottomBorder后,似乎正在調整UITextField的大小,因此該行上使用的UIView現在不夠寬。 很難說為什么看不到更多代碼,但是可以使用幾種方法來克服它。
1)切換到UIView而不是CALayer,並使用自動布局將視圖保持在校正位置。
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的框架/大小都會適當更新。
將此類用於底行文本字段
@IBDesignable class BottomTextField: UITextField {
var lineView = UIView()
@IBInspectable var lineViewBgColor:UIColor = UIColor.gray{
didSet {
if !isFirstResponder {
lineView.backgroundColor = lineViewBgColor
}
}
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)!
setup()
}
override init(frame:CGRect) {
super.init(frame:frame)
setup()
}
// MARK:- Private Methods
private func setup() {
lineView.frame = CGRect(x:CGFloat(0), y:self.frame.size.height-2, width:self.frame.size.width, height:CGFloat(1))
lineView.backgroundColor = lineViewBgColor
self.addSubview(lineView)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.