Scroll UITextView To Bottom

后端 未结 10 1667
误落风尘
误落风尘 2020-12-08 07:26

I am making a an app that has a UITextView and a button.

When I click the button some text will add in the UITextView.

But when c

相关标签:
10条回答
  • 2020-12-08 07:43

    As a generic approach for scrolling to bottom, it can be done on a UIScrollView.

    extension UIScrollView {
        func scrollToBottom() {
            let contentHeight = contentSize.height - frame.size.height
            let contentoffsetY = max(contentHeight, 0)
            setContentOffset(CGPoint(x: 0, y: contentoffsetY), animated: true)
        }
    }
    

    This will work on all descendants of UIScrollView like UITextView, UITableView etc..

    0 讨论(0)
  • 2020-12-08 07:46

    You can use the following code if you are talking about UITextView:

    -(void)scrollTextViewToBottom:(UITextView *)textView {
         if(textView.text.length > 0 ) {
            NSRange bottom = NSMakeRange(textView.text.length -1, 1);
            [textView scrollRangeToVisible:bottom];
         }
    
    }
    

    SWIFT 4:

    func scrollTextViewToBottom(textView: UITextView) {
        if textView.text.count > 0 {
            let location = textView.text.count - 1
            let bottom = NSMakeRange(location, 1)
            textView.scrollRangeToVisible(bottom)
        }
    }
    
    0 讨论(0)
  • 2020-12-08 07:49

    The Swift version of @Hong Duan answer

    func scrollTextViewToBottom(textView: UITextView) {
        if textView.text.count > 0 {
            let location = textView.text.count - 1
            let bottom = NSMakeRange(location, 1)
            textView.scrollRangeToVisible(bottom)
    
            // an iOS bug, see https://stackoverflow.com/a/20989956/971070
            textView.isScrollEnabled = false
            textView.isScrollEnabled = true
        }
    }
    
    0 讨论(0)
  • 2020-12-08 07:52

    With Swift 3

    let bottom = self.textView.contentSize.height - self.textView.bounds.size.height
    self.textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true)
    
    0 讨论(0)
  • 2020-12-08 07:55
    textView.scrollRangeToVisible(NSRange(..<textView.text.endIndex, in: textView.text))
    

    This solution does a couple of notable things slightly different:

    • Utilizes the String.Index interface (likely more performant than e.g. .count)
    • Uses a PartialRangeUpTo which avoids an explicit range start position, reducing the code to a clean one-liner
    0 讨论(0)
  • 2020-12-08 08:00

    You have to implement a delegate method. The code below checks whether a newline has been entered and, if so, scrolls to the bottom of the textView:

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
    
        if ([text isEqualToString:@"\n"]) {
            textView.contentOffset = CGPointMake(0.0, textView.contentSize.height);
        }
        return YES;
    }
    
    0 讨论(0)
提交回复
热议问题