首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使UIScrollView滚动到UITextView的光标位置?

如何使UIScrollView滚动到UITextView的光标位置?
EN

Stack Overflow用户
提问于 2011-05-11 14:45:14
回答 3查看 13.1K关注 0票数 8

我有一个类似于笔记应用程序的视图--即在一张内衬的纸上打字。为了使文本和纸张同时滚动,我禁用了UITextView的滚动,而是将我的UITextView和UIImageView放在UIScrollView中。

唯一的问题是,当用户输入时,文本会消失在键盘下面,因为显然UIScrollView不知道滚动到光标的位置。

有什么简单的方法可以检索光标位置并告诉UIScrollView在那里滚动吗?

--编辑--

从类似的here (有人试图用UITableView做类似的事情)开始,我成功地制作了一个不断增长的、可编辑的、具有固定背景的UITextView,几乎可以完美地滚动。现在唯一的问题是:

如果用户键入速度特别快的话,当文本向上移动时,会有一个略微的抖动。如果用户隐藏键盘,选择屏幕底部的文本,然后再次显示键盘,则必须键入几个字母才能再次显示文本--它不会向上滚动immediately.

  • When用户隐藏键盘,当滚动视图的框架填充屏幕时,动画感觉不太正确。

这是代码-如果有人能进一步完善它,我将非常感激.

代码语言:javascript
运行
复制
#import "NoteEditViewController.h"
#import "RLWideLabelTableCell.h"

@implementation NoteEditViewController
@synthesize keyboardSize;
@synthesize keyboardHideDuration;
@synthesize scrollView;
@synthesize noteTextView;

//
// Dealloc and all that stuff
//
- (void)loadView
{
    [super loadView];
    UIScrollView *aScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView = aScrollView; [aScrollView release];
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, noteTextView.frame.size.height);
    [self.view addSubview:scrollView];
}

- (void)viewDidLoad
{   
    [super viewDidLoad];

    // Get notified when keyboard is shown. Don't need notification when hidden because we are
    // using textViewDidEndEditing so we can start animating before the keyboard disappears.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    // Add the Done button so we can test dismissal of the keyboard    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
        target:self
        action:@selector(doneButton:)];
    self.navigationItem.rightBarButtonItem = doneButton; [doneButton release];

    // Add the background image that will scroll with the text
    CGRect noteImageFrame = CGRectMake(self.view.bounds.origin.x, 
                                       noteTitleImageFrame.size.height, 
                                       self.view.bounds.size.width, 500);    

    UIView *backgroundPattern = [[UIView alloc] initWithFrame:noteImageFrame];
    backgroundPattern.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Notepaper-iPhone-Line"]];
    [self.scrollView addSubview:backgroundPattern];
    [self.view sendSubviewToBack:backgroundPattern];
    [backgroundPattern release];

    // Add the textView
    CGRect textViewFrame = CGRectMake(noteImageFrame.origin.x+27, 
                                      noteImageFrame.origin.y-3, 
                                      noteImageFrame.size.width-35,
                                      noteImageFrame.size.height);

    RLTextView *textView = [[RLTextView alloc] initWithFrame:textViewFrame];
    self.noteTextView = textView; [textView release];
    self.noteTextView.font = [UIFont fontWithName:@"Cochin" size:21];
    self.noteTextView.backgroundColor = [UIColor clearColor];
    self.noteTextView.delegate = self;
    self.noteTextView.scrollEnabled = NO;
    [self.scrollView addSubview:self.noteTextView];
}

- (void)doneButton:(id)sender
{
    [self.view endEditing:TRUE];
}

// When the keyboard is shown, the UIScrollView's frame shrinks so that it fits in the
// remaining space
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    float kbHideDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    self.keyboardHideDuration = kbHideDuration;
    self.keyboardSize = kbSize;
    self.scrollView.frame = CGRectMake(self.view.bounds.origin.x, 
                                       self.view.bounds.origin.y, 
                                       self.view.bounds.size.width, 
                                       self.view.bounds.size.height - kbSize.height);    
}

// When the user presses 'done' the UIScrollView expands to the size of its superview
// again, as the keyboard disappears.
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [UIScrollView animateWithDuration:keyboardHideDuration animations:^{self.scrollView.frame = self.view.bounds;}];
}

// This method needs to get called whenever there is a change of cursor position in the text box
// That means both textViewDidChange: and textViewDidChangeSelection:
- (void)scrollToCursor
{
    // if there is a selection cursor…
    if(noteTextView.selectedRange.location != NSNotFound) {
        NSLog(@"selectedRange: %d %d", noteTextView.selectedRange.location, noteTextView.selectedRange.length);

        // work out how big the text view would be if the text only went up to the cursor
        NSRange range;
        range.location = noteTextView.selectedRange.location;
        range.length = noteTextView.text.length - range.location;
        NSString *string = [noteTextView.text stringByReplacingCharactersInRange:range withString:@""];
        CGSize size = [string sizeWithFont:noteTextView.font constrainedToSize:noteTextView.bounds.size lineBreakMode:UILineBreakModeWordWrap];

        // work out where that position would be relative to the textView's frame
        CGRect viewRect = noteTextView.frame;  
        int scrollHeight = viewRect.origin.y + size.height;
        CGRect finalRect = CGRectMake(1, scrollHeight, 1, 1);

        // scroll to it
        [self.scrollView scrollRectToVisible:finalRect animated:YES];
    }
}

// Whenever the text changes, the textView's size is updated (so it grows as more text
// is added), and it also scrolls to the cursor.
- (void)textViewDidChange:(UITextView *)textView
{
    noteTextView.frame = CGRectMake(noteTextView.frame.origin.x, 
                                    noteTextView.frame.origin.y, 
                                    noteTextView.frame.size.width, 
                                    noteTextView.contentSize.height);
    self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, 
                                             noteTextView.frame.size.height+200);
    [self scrollToCursor];
}

// The textView scrolls to the cursor whenever the user changes the selection point.
- (void)textViewDidChangeSelection:(UITextView *)aTextView 
{
    [self scrollToCursor];
}

// PROBLEM - the textView does not scroll until the user starts typing - just selecting
// it is not enough. 
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self scrollToCursor];
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-05-12 14:58:57

很酷,你找到了我的帖子,很高兴它是有帮助的!

我相信你可能没有看到底线,因为这条底线:

代码语言:javascript
运行
复制
CGRect finalRect = CGRectMake(1, scrollHeight, 1, 1);

你正在创建一个1x1点的盒子。单行文本可能大约有20或30分高(取决于字体大小)。所以,如果你把这个点滚动到可见点,它可能只是显示了底线的最上面的像素--使得底线实际上是不可见的!如果您使finalRect再高一点,使其覆盖整个线路,它可能会运行得更好:

代码语言:javascript
运行
复制
CGRect finalRect = CGRectMake(1, scrollHeight, 1, 30);

另外,您可能一次多次调用scrollRectToVisible代码,这可能会导致“判断器”。在我的代码中,我只从textViewDidChangeSelection运行scrollRectToVisible,并在textViewDidChange中调整UITextView的大小(如果需要的话)。UIScrollView (以及通过继承UITableView)内置支持滚动活动选择的元素以使之可见,在我的测试中,只要在输入时调整UITextView大小(但不是通过触摸选择特定的点),这种方法效果很好。

票数 5
EN

Stack Overflow用户

发布于 2011-05-11 14:53:20

UITextView中找出任何文本或光标的屏幕坐标是不容易的。

您应该做的是注册UIKeyboardWillShowNotificationUIKeyboardWillShowNotification。在回调中,您可以调整sizecontentInsetsUIScrollView,以调整键盘的大小。

通知userInfo中提供了键盘的大小,甚至动画持续时间,所以您可以以一种很好的动画方式来实现它。

您可以在这里找到更多信息和示例代码:http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

票数 1
EN

Stack Overflow用户

发布于 2011-05-11 14:56:54

严格地说,这不是你问题的答案,但下面是一种不同的方法来解决背诵笔记的背景技巧:http://www.cocoanetics.com/2010/03/stuff-you-learn-from-reverse-engineering-notes-app/

我用过了,效果很好。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5966149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档