UITextView starts at Bottom or Middle of the text

后端 未结 19 1555
谎友^
谎友^ 2020-12-04 13:09

I\'ll get right to it. I have a UItextView placed in my view that when needs to scroll to see all the text (when a lot of text is present in the textView) the t

相关标签:
19条回答
  • 2020-12-04 13:29

    Swift 4.2 & Swift 5

    set content offset both before and after setting the text. (on the main Thread)

    let animation = false //or whatever you want
    self.mainTextView.setContentOffset(.zero, animated: animation)
    self.mainTextView.attributedText = YOUR_ATTRIBUTED_TEXT
    self.mainTextView.setContentOffset(.zero, animated: animation)
    
    0 讨论(0)
  • 2020-12-04 13:31

    In my case I was loading a textView in a Custom tableview cell. Below is what I did to make sure the text in a textview loads at the top of the text in my textview in my custom cell.

    1.) In storyboard, set the textview ScrollEnabled = false by unchecking the button.

    2.) You set the isScrollEnabled to true on the textview after the view loads. I set mine in a small delay like below:

    override func awakeFromNib() {
        super.awakeFromNib()
    
    let when = DispatchTime.now() + 1
          DispatchQueue.main.asyncAfter(deadline: when){
            self.textView.isScrollEnabled = true
         }
    
    }
    

    Regardless, if you are in my situation or not, try setting scrollEnabled to false and then when the view loads, set scrollEnabled to true.

    0 讨论(0)
  • 2020-12-04 13:32

    Put this one line of code in ViewDidLoad

    self.automaticallyAdjustsScrollViewInsets = false
    
    0 讨论(0)
  • 2020-12-04 13:33

    I translated zeeple's answer to MonoTouch/Xamarin (C#).

    public override void ViewDidLayoutSubviews()
    {
        base.ViewDidLayoutSubviews();
        myForm.SetContentOffset(new CoreGraphics.CGPoint(0,0), animated: false);
    }
    
    0 讨论(0)
  • 2020-12-04 13:36

    Create an outlet for your UITextView in the ViewController.swift file. In the ViewDidLoad section put the following:

    Swift:

    self.textView.contentOffset.y = 0
    

    I have tried:

    self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
    
    0 讨论(0)
  • 2020-12-04 13:38

    For Swift >2.2, I had issues with iOS 8 and iOS 9 using above methods as there are no single answer that works so here is what I did to make it work for both.

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    
        if #available(iOS 9.0, *) {
            textView.scrollEnabled = false
        }
    
        self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    
        if #available(iOS 9.0, *) {
            textView.scrollEnabled = true
        }
    }
    
    0 讨论(0)
提交回复
热议问题