2013-12-16 3 views
1

프로그래밍 방식으로 사용자 정의 스크롤 객체 (scrollObject)를 사용하여 텍스트 뷰 (textView)를 작성하고 싶습니다.panGestureRecognizer를 사용하여 textView에 대한 사용자 정의 스크롤을 작성하십시오. 프로그래밍 방식으로 모두 프로그래밍 방식으로

이 코드는 스토리 보드와 함께 TextView 및 뷰를 빌드하고 콘센트로 연결할 때도 정상입니다.

그러나 뷰를 프로그래밍 방식으로 빌드하면 아무 일도 발생하지 않습니다.

은 여기 지역 변수 textView, scrollObjectpan을 선포의 .H

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 

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

@end 

입니다 그리고 여기하는 .m에게 viewDidLoad에서

#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); 
     }]; 
    } 
+0

봅니다 viewWillAppear'에 하위 뷰를 추가 :. ' 'viewDidLoad' 대신에'viewDidLoad'에서 프레임 속성을 설정하고 싶지 않습니다. 수퍼 뷰 프레임이 아직 설정되지 않았기 때문에 일반적으로'viewDidLoad'에서 프레임 속성을 설정하지 않으려 고합니다 .. – hgwhittle

+0

고마워, 나는 그것을 시도하지만 아무 일도 일어나지 않는다. 그런데 아무 일도 일어나지 않는다는 것은 textView의 contentOffset이 scrollObject와 상호 작용하지 않는다는 것을 의미합니다. 그러나 scrollObject가 이동합니다 (수직으로 스크롤합니다). – auRegalDesVermines

+0

나는 성취하려고하는 것에 혼란스러워합니다. 'UITe xtView'는'UIScrollView'의 하위 클래스입니다. 즉, 기본적으로 스크롤을 지원합니다. 그래서 당신의'scrollObject'과'pan' 객체는 무엇을 위해 사용되고 있습니까? – hgwhittle

답변

0

입니다. 제스처 인식기 메소드가 호출와 "아무 일도 일어나지 않는다"때 그들은 nil을 그래서 헤더 파일에 선언

속성이 설정되지 않습니다 당신은 nil 메소드를 호출 할 때. 있는 viewDidLoad에서

, UITextView *textView = ...선언 당신이 헤더에 선언 재산에 아무런 관련이없는 지역 변수입니다. 대신

@synthesize을 수행하고 viewDidLoad에, 은 재산 대신 설정 :

self.textView = ... 

scrollObject에 대해 동일한 작업을 수행합니다.


그건 그렇고, 당신은 속성으로 pan를 선언하거나 바르 할 필요가 없습니다 나는 그것을 (viewDidLoad)에서 지역 변수로 남겨을 제거 할

+0

정말 고마워요! – auRegalDesVermines