问题
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.
回答1:
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!
回答2:
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)
}
来源:https://stackoverflow.com/questions/43322541/swift-scroll-a-uitextview-horizontally