UITextField placeholder text: adjust to fit

后端 未结 1 505
不思量自难忘°
不思量自难忘° 2021-02-12 10:32

I have UITextField with longer text in it set as placeholder. What I want is for this placeholder text to adjust its font size when the width of field is too sm

相关标签:
1条回答
  • 2021-02-12 11:14

    You can create a subclass of UITextField:

    class AutoSizeTextField: UITextField {
        override func layoutSubviews() {
            super.layoutSubviews()
    
            for subview in subviews {
                if let label = subview as? UILabel {
                    label.minimumScaleFactor = 0.3
                    label.adjustsFontSizeToFitWidth = true
                }
            }
        }
    }    
    

    Or you can just add some code in your view controller's viewDidAppear:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        for subview in fieldTest.subviews {
            if let label = subview as? UILabel {
                label.minimumScaleFactor = 0.3
                label.adjustsFontSizeToFitWidth = true
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题