使用panGestureRecognizer为textView构建自定义滚动:全部以编程方式

时间:2013-12-16 16:33:41

标签: ios uitextview uipangesturerecognizer

我想用自定义滚动对象(scrollObject)构建一个文本视图(textView),但都是以编程方式构建的。

当我使用故事板构建textView和View以及将它们作为Outlets连接时,此代码是可以的。

但是当我以编程方式构建视图时,没有任何反应。

这是.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic,strong) UITextView *textView;
@property (nonatomic,strong) UIView *scrollObject;
@property UIPanGestureRecognizer *pan;

@end

这是.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UITextView *textView =[[UITextView alloc]initWithFrame:CGRectMake(0, 0, 618,1024)];
    [self.view addSubview:textView];

    UIView *scrollObject =[[UIView alloc]initWithFrame:CGRectMake(650, 50, 85, 80)];
    [self.view addSubview:scrollObject];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlepan:)];
    [scrollObject addGestureRecognizer:pan];
}

- (void)handlepan:(UIPanGestureRecognizer *)pan {
    static CGPoint initialCenter;
    if (pan.state == UIGestureRecognizerStateBegan)
    {
        initialCenter = pan.view.center;
    }
    CGPoint translation = [pan translationInView:self.view];
    pan.view.center = CGPointMake(initialCenter.x, initialCenter.y + translation.y);
    NSLog(@"_scrollObject.center.y: %f",_scrollObject.center.y); //here is the problem : return 0 !      
    [UIView animateWithDuration:0.1 animations:^{
                _textView.contentOffset = CGPointMake(0, (_scrollObject.center.y)*_textView.contentSize.height/1000);
        }];
    }

1 个答案:

答案 0 :(得分:0)

viewDidLoad中,您要声明本地变量textViewscrollObjectpan

在头文件中声明的属性永远不会被设置,因此当调用手势识别器方法时它们是nil并且当您在nil上调用方法时“没有任何反应”

在viewDidLoad中,UITextView *textView = ... 声明一个本地变量,该变量与您在标头中声明的属性无关。

相反,请执行@synthesize,然后在viewDidLoad设置该属性:

self.textView = ...

scrollObject执行相同操作。


顺便说一下,您不需要将pan声明为属性或ivar,我会将其删除(将其保留为viewDidLoad)中的局部变量。