Resize a UITextField while typing (by using Autolayout)

后端 未结 9 1755
梦如初夏
梦如初夏 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:48

    First things first: in Swift 4, UITextField's intrinsicContentSize is a computed variable, not a method.

    Below is a Swift4 solution with a specialized use case. A right justified textfield can resize and extend leftward up to a certain pixel boundary. The textfield is assigned to the CurrencyTextField class which inherits from UITextField. CurrencyTextField is then extended to provide custom behavior for returning the object's intrinsicContentSize, a computed variable. .
    The "editing changed" event of the CurrencyTextField instance is mapped to the repositionAndResize IBAction method in its host UIViewController class. This method simply invalidates the current intrinsic content size of the CurrencyTextField instance. Invoking the CurrencyTextField's invalidateIntrinsicContentSize method ( inherited form UITextField ) triggers an attempt to get the object's intrinsic content size.

    The custom logic in CurrencyTextField's intrinsicContentSize getter method has to convert the CurrentTextField's text property to NSString in order ascertain its size, which it returns as the intrinsicContentSize if the x coordinate of the CurrencyTextField is greater than the stipulated pixel boundary.

    class CurrencyTextField:UITextField {
    
    }
    
    extension CurrencyTextField {
    
    
         override open var intrinsicContentSize: CGSize {
    
            if isEditing {
                let string = (text ?? "") as NSString
                let stringSize:CGSize = string.size(withAttributes: 
                 [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 
                 19.0)])
                 if self.frame.minX > 71.0 {
                    return stringSize
                 }
           }
    
           return super.intrinsicContentSize
        }
    
    
    }
    
    class TestController: UIViewController {
    
        @IBAction func repositionAndResize(_ sender: CurrencyTextField) {
            sender.invalidateIntrinsicContentSize()
        }
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
    
    }
    

提交回复
热议问题