Resize a UITextField while typing (by using Autolayout)

后端 未结 9 1760
梦如初夏
梦如初夏 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条回答
  •  萌比男神i
    2020-12-04 13:29

    I don't know why UITextField only updates its intrinsicContentSize when it resigns its first responder status. This happens for both iOS 7 and iOS 8.

    As a temporary solution, I override intrinsicContentSize and determine the size using typingAttributes. This accounts for leftView and rightView as well

    // This method is target-action for UIControlEventEditingChanged
    func textFieldEditingChanged(textField: UITextField) {
      textField.invalidateIntrinsicContentSize()
    }
    
    
    override var intrinsicContentSize: CGSize {
        if isEditing {
          let string = (text ?? "") as NSString
          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
      }
    

    Here I make the it wider to account for the caret

提交回复
热议问题