2

I want to display selected contacts on a label which could be scrolled like in Snapchat. After going through lot of questions on stackoverflow I have used Textview since it is scrollable.

@IBOutlet weak var selectedContactsDisplay: UITextView!
selectedContactsDisplay.delegate = self
selectedContactsDisplay.backgroundColor = UIColor.appColor()     
selectedContactsDisplay.textColor = UIColor.white
selectedContactsDisplay.textContainer.maximumNumberOfLines = 1
selectedContactsDisplay.textContainer.lineBreakMode = NSLineBreakMode.byTruncatingHead

let stringOne = selectedContactName.joined(separator: ",")
selectedContactsDisplay.text = stringOne

func textViewDidBeginEditing(_ textView: UITextView) {
    textView.resignFirstResponder()
}

But, the horizontal scrolling is still not possible. Can someone help me on how can the enable the scrolling.

Ananth
  • 31
  • 1
  • 4

2 Answers2

3

You can not scroll in a TextView by yourself, what you can do is to enable autoScroll:

@IBOutlet weak var selectedContactsDisplay: UITextView!
selectedContactsDisplay.delegate = self
selectedContactsDisplay.backgroundColor = UIColor.appColor()     
selectedContactsDisplay.textColor = UIColor.white
selectedContactsDisplay.textContainer.maximumNumberOfLines = 1
selectedContactsDisplay.textContainer.lineBreakMode = NSLineBreakMode.byTruncatingHead


let stringOne = selectedContactName.joined(separator: ",")
selectedContactsDisplay.text = stringOne

func textViewDidBeginEditing(_ textView: UITextView) {
    textView.resignFirstResponder()
let range = NSMakeRange(selectedContactsDisplay.text.characters.count - 1, 0)
selectedContactsDisplay.scrollRangeToVisible(range)
}
Aitor Pagán
  • 423
  • 7
  • 18
2

You can not scroll horizontally in UITextView. For solution you can take a UIScrollView which can scroll horizontally and can add label or textfield in to it and increase width of that label according to your content! Proper constraint should be set!

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
  • Thank you so much. I have managed to do it the way you suggested. – Ananth Apr 10 '17 at 12:56
  • I have a question. Now, How do I scroll to the end of the label text. Right now, even when I add new data, It is only showing the beginning part of the text. – Ananth Apr 10 '17 at 13:22
  • you need to calculate your label's width and set frame of label to that width! – Ketan Parmar Apr 10 '17 at 13:23
  • Does UILabel accept input? Can the user type in UILabel and add and change the text content? – daniel Feb 21 '23 at 12:49