Swift: Scroll a UITextView horizontally

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-10 09:37:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!