Question

I would like to build a text view (textView) with a custom scroll object (scrollObject), but all programmatically.

This code is OK when I build a textView and a View with the storyboard and when I connect them as Outlets.

But when I build the views programmatically, nothing happens.

Here is the .h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

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

@end

And here is the .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);
        }];
    }
Was it helpful?

Solution

In viewDidLoad, you are declaring local variables textView, scrollObject, and pan.

The properties declared in the header file are never set so they are nil when the gesture recognizer method is called and "nothing happens" when you call methods on nil.

In viewDidLoad, UITextView *textView = ... is declaring a local variable that has no connection to the property you declared in the header.

Instead, do @synthesize, and in viewDidLoad, set the property instead:

self.textView = ...

Do the same for scrollObject.


By the way, you don't need to declare pan as a property or ivar and I would remove it (leave it as a local variable in viewDidLoad).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top