2011-09-01 77 views
6

我想使我的uitextview在应用程序启动时自动滚动。任何人都可以帮我一个详细的代码?我是iPhone SDK的新手。使uitextview以编程方式滚动

+0

究竟如何你想让它滚动?你想让它滚动到最后,还是中间的一个点?或者你想让它从上到下缓慢滚动? – mahboudz

+0

http://stackoverflow.com/questions/1088960/iphone-auto-scroll-uitextview-but-allow-manual-scrolling-also可能的副本 – tipycalFlow

+0

我想从上到下滚动uitextview,慢慢地。并且没有允许textview交互。我的意思是,用户不能在textview中编辑任何东西。 – user919050

回答

12

.h文件中

@interface Credits : UIViewController 
{ 
    NSTimer *scrollingTimer; 

    IBOutlet UITextView *textView; 


} 
@property (nonatomic , retain) IBOutlet UITextView *textView; 

- (IBAction) buttonClicked ; 

- (void) autoscrollTimerFired; 

@end 

.m文件

- (void) viewDidLoad 
{  
    // it prints the initial position of text view 
    NSLog(@"%f %f",textView.contentSize.width , textView.contentSize.height); 

    if (scrollingTimer == nil) 
    { 
     // A timer that updates the content off set after some time so it can scroll 
     // you can change time interval according to your need (0.06) 
     // autoscrollTimerFired is the method that will be called after specified time interval. This method will change the content off set of text view 
     scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:(0.06) 
         target:self selector:@selector(autoscrollTimerFired) userInfo:nil repeats:YES];   
    } 
} 

- (void) autoscrollTimerFired 
{ 
    CGPoint scrollPoint = self.textView.contentOffset; // initial and after update 
    NSLog(@"%.2f %.2f",scrollPoint.x,scrollPoint.y); 
    if (scrollPoint.y == 583) // to stop at specific position 
    { 
     [scrollingTimer invalidate]; 
     scrollingTimer = nil; 
    } 
    scrollPoint = CGPointMake(scrollPoint.x, scrollPoint.y + 1); // makes scroll 
    [self.textView setContentOffset:scrollPoint animated:NO]; 
    NSLog(@"%f %f",textView.contentSize.width , textView.contentSize.height); 

} 

希望它可以帮助你....

+0

是啊...你需要在.m文件中的许多地方使用的变量..在上面的代码中的ScrollingTimer,textView你必须在.h文件中声明 – Maulik

+0

我将在StackOver流程中提供..:D – Maulik

+1

感谢解决方案。我开发了一个自定义键盘,为此,您的代码在UITextView中帮助了我。 –

1

UITextView派生自UIScrollview,因此您可以使用-setContentOffset:animated:设置滚动位置。

假设你想以每秒10点的速度顺利滚动,你会做类似的事情。

- (void) scrollStepAnimated:(NSTimer *)timer { 
    CGFloat scrollingSpeed = 10.0; // 10 points per second 
    NSTimeInterval repeatInterval = [timer timeInterval]; // ideally, something like 1/30 or 1/10 for a smooth animation 

    CGPoint newContentOffset = CGPointMake(self.textView.contentOffset.x, self.textView.contentOffset.y + scrollingSpeed * repeatInterval); 
    [self.textView setContentOffset:newContentOffset animated:YES]; 
} 

当然,您必须设置计时器,并确保在视图消失时取消滚动等等。

+0

你必须声明NSTimer为实例变量,并在-viewWillAppearAnimated:中设置一个好看的重复间隔。然后确保无效并在-dealloc和-viewWillDisappearAnimated:中释放它。 –

+0

我不能给你完整的代码,因为我不确定你了解代码在做什么。一定要尝试理解该代码背后的逻辑。它正在做的只是滚动到底部给定一个特定的速度。 –

+0

在你的.h文件中,你必须做这样的事情,你声明你的其他实例变量:NSTimer * scrollingTimer; @Maulik向您展示了如何设置和使计时器无效。 –