Search code examples
iosswiftstoryboardnslayoutconstraint

how can I add a button (programatically or in storyboard) right next to my text view in Swift?


I'm writing a swift ios app and I introduced this textView: https://github.com/KennethTsang/GrowingTextView

In my code I added InputToolbar with one item:

enter image description here

and then included the code:

    let textView = GrowingTextView()
    textView.delegate = self
    textView.layer.cornerRadius = 4.0
    textView.maxLength = 200
    textView.maxHeight = 70
    textView.trimWhiteSpaceWhenEndEditing = true
    textView.placeHolder = "Write a comment..."
    textView.placeHolderColor = UIColor(white: 0.8, alpha: 1.0)
    textView.placeHolderLeftMargin = 5.0
    textView.font = UIFont.systemFontOfSize(15)

    inputToolbar.translatesAutoresizingMaskIntoConstraints = false
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.returnKeyType = UIReturnKeyType.Send
    inputToolbar.addSubview(textView)
    let views = ["textView": textView]
    let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[textView]-8-|", options: [], metrics: nil, views: views)
    let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-8-[textView]-8-|", options: [], metrics: nil, views: views)
    inputToolbar.addConstraints(hConstraints)
    inputToolbar.addConstraints(vConstraints)

so now there's a full-width textview there. How could I add a button right next to the text view? For example in whatsapp there's this small microphone next to the textview:

enter image description here


Solution

  • Ok, here's how you add a UITextView with additional buttons to a UIToolBar:

    You add a UIView to the UIToolBar. Afterwards you can add a UITextView to the UIView that resides in the UIToolBar.

    Then you can set the Custom Class of the UITextView to GrowingTextView (https://github.com/KennethTsang/GrowingTextView).

    Here's a screenshot of my storyboard.

    GrowingTextView inside UIToolBar with additional buttons

    Let me know if that helps.