I am working on a project where I require to make UITextView horizontally scrollable.The problem statement is defined below
I have tried putting the UITextview within a ScrollView for horizontal scroll as suggested in other similar question solution on Stack Overflow, while the scroll works there are multiple issues related to cursor position like:
- Dynamically setting the width of UITextView to match the width of content's biggest line (achievable)
- Cursor doesn't show on the screen when content increase or decrease i.e while adding content in same line or deleting content in between, cursor position is not handled by UITextView perfectly the cursor jumps to line start and comes back to current position, and is not visible on screen.
- UITextView should only be able to scroll Horizontally or Vertically.(Need to disable the diagonal scroll).
Attaching the current code I am experimenting with, also tried other answers in similar questions, doesn't work.:
class ViewController: UIViewController, UITextViewDelegate, UIScrollViewDelegate {
@IBOutlet weak var scroll:UIScrollView!
@IBOutlet weak var textView:UITextView!
var displayStr = ""
var strSize:CGRect!
var font:UIFont!
var maxSize:CGSize!
override func viewDidLoad() {
super.viewDidLoad()
displayStr = textView.text
textView.delegate = self
scroll.delegate = self
scroll.addSubview(textView)
textView.isEditable = true
textView.isScrollEnabled = false
maxSize = CGSize(width: 9999, height: 9999)
font = UIFont(name: "Menlo", size: 16)!
textView.font = font
updateWidth()
}
func updateWidth() {
strSize = (displayStr as NSString).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font!], context: nil)
if strSize.width > self.view.frame.width {
textView.frame = CGRect(x: 0, y: 0, width: strSize.width + 50, height: view.frame.height+10)
}
scroll.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: view.frame.height)
scroll.contentSize = CGSize(width: strSize.width + 30, height: strSize.height)
}
func textViewDidChange(_ textView: UITextView) {
updateWidth()
}
This is how my output looks