I need to set up a TextField that automatically changes its width while typing. The size of textfield should change dynamically. I found the following solution but not getting how to use it exactly Resize textField Based On Content
Asked
Active
Viewed 1,806 times
1 Answers
-1
You have to use UITextView
for this and use it's sizeThatFits
method.
First you have to know how high line will go
var totalLines:CGFloat = 5
var maxHeight:CGFloat = myTextview.font.lineHeight * totalLines
Then in your viewDidLoad
method
myTextView.sizeThatFits(CGSizeMake(myTextview.frame.size.width, maxHeight))
You are doing wrong in your code. use this above code in viewDidLoad
@IBOutlet weak var myTextview: UITextView!
override func viewDidLoad()
{ super.viewDidLoad()
let totalLines:CGFloat = 5
let maxHeight:CGFloat = (myTextview.font!.lineHeight * totalLines)
myTextview.sizeThatFits(CGSizeMake(myTextview.frame.size.width, maxHeight))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
}

hellosheikh
- 2,929
- 8
- 49
- 115
-
Compilation fails with the message " Instance member 'myTextview' cannot be used on type 'ViewController'". Not getting how to resolve it? – Jan 05 '16 at 07:12
-
here use your textfield name. I have used it mytextfield as an example @dimple – hellosheikh Jan 05 '16 at 07:17
-
ya...i used my textview name...I have set outlet for textview with "myTextview" name – Jan 05 '16 at 07:20
-
@dimple could you please share your viewController code here – hellosheikh Jan 05 '16 at 07:23
-
import UIKit class ViewController: UIViewController { @IBOutlet weak var myTextview: UITextView! var totalLines:CGFloat = 5 var maxHeight:CGFloat = (myTextview.font.lineHeight * totalLines) override func viewDidLoad() { super.viewDidLoad() myTextView.sizeThatFits(CGSizeMake(myTextview.frame.size.width, maxHeight)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } – Jan 05 '16 at 07:33
-
i got answer here ...http://stackoverflow.com/questions/34605939/instance-member-mytextview-cannot-be-used-on-type-viewcontroller/34606327#34606327...thanks But textfield is not autoresize during typeing..ie above code is not working as i desire – Jan 05 '16 at 07:42
-
@dimple you were doing it wrong. Please check my updated answer and mark it correct if it solves your problem – hellosheikh Jan 05 '16 at 07:45
-
@ hellosheikh..i have used your updated code but still my textview is not autoresizing during typing – Jan 05 '16 at 07:49
-
@dimple did answer here work for you .stackoverflow.com/questions/34605939/ ? – hellosheikh Jan 05 '16 at 07:52
-
..No stackoverflow.com/questions/34605939/ this answer is also not working for me – Jan 05 '16 at 07:54
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/99775/discussion-between-hellosheikh-and-dimple). – hellosheikh Jan 05 '16 at 07:55