UITextfield is clipped at the top, in edit mode

I got two UIText fields with a separator (UILabel) between them. I put them all in UIStackView.

In edit mode, the content of the text box is clipped at the top as shown in the picture below

enter image description here

I found that the only way to fix this problem is to make this separator big enough, but that messes up my design.

How to fix it?

It is worth mentioning the UIStackView settings:

enter image description here

and show how I am implementing this custom UITextfield in a lower level style

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

      

}

Any help is greatly appreciated

EDIT

I have another TextField and it works great, but it doesn't sit inside a horizontal UIStackView. Here is a screenshot of the hierarchy:

enter image description here

enter image description here

+3


source to share


1 answer


Sorry, you need to check the size when editing



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

      

0


source







All Articles