简体   繁体   中英

Adjusting text view height while editing Swift

I am not using a table view and my text view is not inside a table view cell. I have been researching this for days but nothing has worked and most answers relate to changing the height of a text view inside a table view cell or only work for iOS 6 and prior.

I am trying to adjust the height of a text view while the user types in it. I and using auto layout and have an outlet connected to the text view height constraint and I have tried to get this working by altering that but it doesn't have any affect.

If anybody has gotten this working on iOS 7 or newer and can give me some advise I would really appreciate it!

The idea is to set up a height constraint on the TextView, add key value observer for contentSize property of a textview, and then manipulate the height constraint of a TextView on each contentSize change. Please find a demo project here https://github.com/achikin/adjustabletextview

Look at the UITextViewDelegate methods, especially at - textViewDidChange: method. Detect text changes on your textView , then adjust its height like so:

Objective-C:

CGRect frame;
frame = textiew.frame;
frame.size.height = [textView contentSize].height;
textView.frame = frame;

Swift:

let frame = textView.frame
frame.size.height = textView.contentSize.height
textView.frame = frame

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM