user6423177
user6423177

Reputation:

Place UIButton at the end of text in UITextView in iOS app in Xcode written in Swift

In one ViewController of my app there's a UITextView. I want to have an "Allow Push Notifications" button at the end of the text. But since a button is static a the text in the TextView is dynamical depending on display width it looks really bad on some devices and orientations.

Does anybody know how to solve this problem? Is there a possibility to insert a button in a TextView. Or can I align the button depending from TextView content height?

Regards, David.

Upvotes: 2

Views: 5502

Answers (1)

Danny Bravo
Danny Bravo

Reputation: 4658

UITextView subclasses from UIScrollView, you can use this to your advantage to add subviews to it as you would any normal UIScrollView, the trick is to offset the text view's text container by the height of the button + padding. For example:

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 500))
textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae fermentum tellus. Donec dui sem, viverra eu auctor eleifend, aliquet id lorem. Nam id sapien sed arcu auctor commodo nec nec nulla. Praesent id mi nec odio consequat varius id sit amet quam."

let buttonHeight: CGFloat = 44
let contentInset: CGFloat = 8

//inset the textView
textView.textContainerInset = UIEdgeInsets(top: contentInset, left: contentInset, bottom: (buttonHeight+contentInset*2), right: contentInset)

let button = UIButton(frame: CGRect(x: contentInset, y: textView.contentSize.height - buttonHeight - contentInset, width: textView.contentSize.width-contentInset*2, height: buttonHeight))

//setup your button here
button.setTitle("BUTTON", forState: UIControlState.Normal)
button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
button.backgroundColor = UIColor.lightGrayColor()

//Add the button to the text view
textView.addSubview(button)

This will give you the following output:

enter image description here

Hope this helps!

Upvotes: 7

Related Questions