Resize a UITextField while typing (by using Autolayout)

后端 未结 9 1752
梦如初夏
梦如初夏 2020-12-04 13:05

I have a UITableViewCell which has two UITextFields (without borders). The following constraints are used to set up the horizontal layout.

@\"|-10-[leftTextFi

9条回答
  •  离开以前
    2020-12-04 13:49

    Here's the answer in Swift. As a bonus, this snippet doesn't collapse the text field if there is a placeholder.

    // UITextField subclass
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.addTarget(self, action: #selector(textFieldTextDidChange), forControlEvents: .EditingChanged)
    }
    
    func textFieldTextDidChange(textField: UITextField) {
        textField.invalidateIntrinsicContentSize()
    }
    
    override func intrinsicContentSize() -> CGSize {
        if self.editing {
            let textSize: CGSize = NSString(string: ((text ?? "" == "") ? self.placeholder : self.text) ?? "").sizeWithAttributes(self.typingAttributes)
            return CGSize(width: textSize.width + (self.leftView?.bounds.size.width ?? 0) + (self.rightView?.bounds.size.width ?? 0) + 2, height: textSize.height)
        } else {
            return super.intrinsicContentSize()
        }
    }
    

提交回复
热议问题