Benjamin Hviid Benjamin Hviid - 15 days ago 7
Swift Question

Disable horizontal scroll in UITextView (iOS)

I've been trying to figure out how to disable horizontal scrolling in a UITextView (I've seen many questions about this, but none of them have helped me). The scrolling issue occurs when I rotate the textview. The code used for this is here:

class ViewController: UIViewController {

@IBOutlet var textView: UITextView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 10) // prevent that text near right edge it cut away
textView.contentSize = CGSizeMake(textView.frame.size.width, 300)
self.textView.transform = CGAffineTransformMakeRotation(2 * 3.14159 / 180.0)
textView.layer.borderWidth = 1.0 // check that textview stays within view
textView.layer.borderColor = UIColor.blackColor().CGColor
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


I have tried to disable the horizontal scrolling by setting
textView.contentSize = CGSizeMake(textView.frame.size.width, 300)
as suggested in another stackoverflow question, but it doesn't have any effect. I've also tried to remove the inset, but it didn't lock the horizontal scrolling either.

I need to be able to scroll vertically, so to disable scrolling entirely is not an option. I'm using Xcode 6 with iOS 8 as deployment target.

Answer

You have to to set the content size to the actual size, and do it a little later in the process, in viewDidAppear.

- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  self.textView.contentSize = self.textView.bounds.size;
}
Comments