【问题标题】:Bottom Border Width on Swift TextField in TableViewTableView中Swift TextField的底部边框宽度
【发布时间】:2017-06-06 08:38:39
【问题描述】:

我构建了一个静态表格视图,其中的行数比屏幕上的多,因此用户必须滚动才能查看所有单元格。

每个单元格都有一个带有以下类的文本字段来添加底部边框:

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
   }
}

我在从服务器 e 接收到一些数据后调用该方法。 g.

self.firstnameTextField.text = firstNameFromDB
self.firstnameTextField.addBottomBorder(color: .blue)

这适用于当前显示的每个单元格。但是当前视图之外的单元格比文本字段短。 看这个截图,对于“Vorname”,意味着 firstName 一切看起来都不错,但是对于电子邮件、密码等,边框很短。 http://share-your-photo.com/34b5e80253

【问题讨论】:

    标签: ios swift tableview border textfield


    【解决方案1】:

    看起来 UITextField 的大小在您调用 addBottomBorder 后正在调整大小,因此该行使用的 UIView 现在不够宽。在没有看到更多代码的情况下很难说为什么会出现这种情况,但是您可以使用多种方法来克服它。

    1) 切换到 UIView 而不是 CALayer 并使用自动布局将视图保持在更正位置。

    2) 覆盖layoutSubviews,更新底线的frame。

    对你来说最简单的可能是选项 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 的框架/大小都会相应更新。

    【讨论】:

      【解决方案2】:

      将此类用于底线文本字段

      @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)
          }
      
      }
      

      【讨论】:

      • 虽然这可能是一种更好的方法,但它会遇到同样的问题,因为底线的框架仅在创建时设置,因此如果文本字段更改框架,底线将不会反映变化。
      猜你喜欢
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      相关资源
      最近更新 更多