1

I would like to autoresize UITextView similar to sms-app or whatsapp. I only found solution for objective-c and the example projects have too many code. I need this in Swift.

Q: How can I resize the UITextView by font size while user is typing a message with linebreak?

masterWN
  • 85
  • 1
  • 9

2 Answers2

3

You can do this with UITextViewDelegate. I don't know how to achieve this with AutoLayout.

func textViewDidChange(textView: UITextView)
    {
        var fixedWidth : CGFloat = textView.frame.size.width
        var newSize : CGSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat(MAXFLOAT)))
        var newFrame : CGRect = textView.frame
        newFrame.size = CGSizeMake(CGFloat(fmaxf((Float)(newSize.width), (Float)(fixedWidth))),newSize.height)

        textView.frame = newFrame
    }
Alvin Varghese
  • 842
  • 10
  • 33
  • Thank you Alvin. With autolayout this does not work. I found a objective-c library using autolayout. Importing this to my Swift project solved my Problem. The library is on github: https://github.com/MatejBalantic/MBAutoGrowingTextView – masterWN Mar 24 '15 at 12:20
0
var textStorage: NSTextStorage!
var layoutManager: NSLayoutManager!
var textContainer: NSTextContainer!
var textPreview: UITextView!

 override func viewDidLoad() {
    super.viewDidLoad()

    textStorage = NSTextStorage()
    layoutManager = NSLayoutManager()
    textStorage.addLayoutManager(layoutManager)

    let newTextViewRect = view.bounds
    let containerSize = CGSize(width: newTextViewRect.width, height: CGFloat.max + 5)

    textContainer = NSTextContainer(size: containerSize)
    layoutManager.addTextContainer(textContainer)

    textPreview = UITextView(frame: newTextViewRect, textContainer: textContainer)
    textPreview.font = UIFont(name: "Helvetica", size: 16)
    view.addSubview(textPreview)

    configureView()

    let length = count(textPreview.text)
    let range:NSRange = NSMakeRange(length , 1)
    textPreview.scrollRangeToVisible(range)

}

override func viewDidLayoutSubviews() {
    textPreview.frame = view.bounds
}
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
nuknuk
  • 1