0

I want to add a dynamic textfield when a user clicks somewhere on the view.textfield should increase the size as the user types. Currently i am using the below code

textfield = UITextField(frame: rect)
            textfield.backgroundColor = UIColor.clear
            textfield.layer.borderColor = UIColor.clear.cgColor
            textfield.autocorrectionType = UITextAutocorrectionType.no
            textfield.textColor = UIColor.blue
            textfield.textAlignment = .right
            textfield.layer.borderWidth = 1.0
            textfield.delegate = self
            textfield.becomeFirstResponder()

But this textfield is not automatically increasing height and width.

Faheem Rahman
  • 343
  • 2
  • 10

2 Answers2

1

You can try

class ViewController: UIViewController , UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.delegate = self 
    }

   func textViewDidChange(_ textView: UITextView) {

       let ff = textView.text! as NSString

       let rr = ff.size(withAttributes: [NSAttributedStringKey.font:UIFont(name: "Helvetica", size: 17)])

       textView.frame = CGRect(origin: textView.frame.origin, size: rr)
   }

}

//

Arabic

func textViewDidChange(_ textView: UITextView) {

    let ff = textView.text! as NSString

   let rr = ff.size(withAttributes: [NSAttributedStringKey.font:UIFont(name: "Helvetica", size: 17)!])

    textView.frame = CGRect(origin:CGPoint(x: self.view.frame.width - rr.width, y: textView.frame.origin.y), size: rr)

 }

enter image description here

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Follow the below steps to work.

  1. create UITextView on clicking on the view as you are creating UITextField now.
  2. set delegate and implement the delegate method(s) like 'textViewDidChange' or 'UITextViewTextDidChange'notification to get the callback when text changes.
  3. inside the callback method set the UITextView frame width and height to its content size property's width and height ! happy coding !

If need more help do let me know.

vivekDas
  • 1,248
  • 8
  • 12
  • I tried this code. func textViewDidChange(_ textView: UITextView) { textView.frame = CGRect(origin: textView.frame.origin, size: textView.contentSize) } But only the height is increasing, not the width. I need both – Faheem Rahman Jul 16 '18 at 10:21
  • what is your initial width for the UITextView ? see contentSize calculation is based on the width you provide initially to the UITextView. So basically width is fixed and contentSize gives you the required height. To achieve what you want, you have to calculate the text width programmatically, then you must have a max width value,so now if the width increases the max width then fix the UITextView width and just increase the height what you get from contentSize property. – vivekDas Jul 16 '18 at 10:28