在编辑模式下,UITextfield从顶部剪切

时间:2017-03-21 22:36:22

标签: ios swift uitextfield uistackview

我有两个UITextfields,它们之间有分隔符(UILabel)。 我将它们全部放入UIStackView。

在编辑模式下,文本字段的内容从顶部剪切,如下图所示

enter image description here

我发现删除此问题的唯一方法是让这个分隔符足够大,但这会破坏我的设计。

如何解决?

值得一提的是我的UIStackView设置:

enter image description here

并展示我如何实现这个自定义底线式UITextfield

class CustomTextField: UITextField {

override func awakeFromNib() {
    super.awakeFromNib()

    let attributedString = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName:UIColor.lightGray, NSFontAttributeName: UIFont(name: "GothamRounded-Book", size: 18.0)! ])
    self.attributedPlaceholder = attributedString
    self.tintColor = UIColor.appRed
    self.font = UIFont(name: "GothamRounded-Book", size: 18.0)!
    self.borderStyle = .none
    self.textAlignment = .center

}


override func textRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: 0, dy: 5)
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return bounds.insetBy(dx: 0, dy: 5)
}


override var tintColor: UIColor! {

    didSet {
        setNeedsDisplay()
    }
}

override func draw(_ rect: CGRect) {

    let startingPoint   = CGPoint(x: rect.minX, y: rect.maxY)
    let endingPoint     = CGPoint(x: rect.maxX, y: rect.maxY)

    let path = UIBezierPath()

    path.move(to: startingPoint)
    path.addLine(to: endingPoint)
    path.lineWidth = 2.0

    tintColor.setStroke()
    tintColor = UIColor.appRed

    path.stroke()
}

}

任何帮助非常感谢

修改

我有另一个像这样的TextField,它工作正常,但它不会位于任何水平UIStackView内。以下是层次结构的屏幕截图:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

不幸的是,您需要在编辑时检查尺寸

class CustomTextField: UITextField {
   override func awakeFromNib() {
      super.awakeFromNib()
      self.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
   }

   func textFieldEditingChanged(_ textField: UITextField) {
      textField.invalidateIntrinsicContentSize()
   }


   override var intrinsicContentSize: CGSize {
      if isEditing {
         let string = text ?? ""
         let size = string.size(attributes: typingAttributes)
         return CGSize(width: size.width + (rightView?.bounds.size.width ?? 0) + (leftView?.bounds.size.width ?? 0) + 2,
                       height: size.height)
      }

      return super.intrinsicContentSize
   }
}
相关问题