属性访问器方法实现

时间:2013-03-15 21:17:40

标签: ios objective-c properties

我正在尝试在rood VC的viewdidload中提供另一个自定义视图。

MSHView *customTextView = [[MSHView alloc] initWithFrame:self.view.bounds];
customTextView.textView.text = @"abc";
[customTextView layoutSubviews];
[self.view addSubview:customTextView];

MSHView头文件:

@property(nonatomic, strong) UITextView * textView;
@property (nonatomic, strong) UIImageView* translucentIV;

MSHView实施文件:

-(UIImageView*) translucentIV {
    if(!_translucentIV) {
        _translucentIV.frame = self.frame;
        //NSLog(@"frame for translucent IV, %@", _translucentIV.frame);
        _translucentIV.backgroundColor = [UIColor whiteColor];
        _translucentIV.alpha = 0.5;
    }
    return _translucentIV;
}

-(UITextView* ) textView{
    if(!_textView){
        /*
        float height = self.bounds.size.height - 5;
        float width = self.bounds.size.width - 5;
        _textView.frame = CGRectMake(5,5,width,height);
        _textView.text = @"test text";
         */
        NSLog(@"textview property being initialized");
    }
    return _textView;
}

-(void)layoutSubviews {
    self.textView.frame = self.frame;
    self.translucentIV.backgroundColor = [UIColor whiteColor];
    self.alpha = 0.5;
    NSString *abc = @"abc";
    self.textView.text = [NSString stringWithFormat:@"%@",abc];
    NSLog(@"layout subview being called");
}


-(void) setTextView:(UITextView *)textView {
    if(textView != _textView) {
        _textView = textView;
        _textView.text = @"setter method called";
    }

}

仍无法从MSHView中看到textview。我想我没有正确地做房产。任何帮助或解释?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您没有创建UIImageViewUITextView

尝试更多类似的内容:

-(UIImageView*) translucentIV {
    if(!_translucentIV) {
        _translucentIV = [[UIImageView alloc] initWithFrame:self.frame];
        //NSLog(@"frame for translucent IV, %@", _translucentIV.frame);
        _translucentIV.backgroundColor = [UIColor whiteColor];
        _translucentIV.alpha = 0.5;
    }
    return _translucentIV;
}

-(UITextView *)textView {
    if(!_textView) {
        float height = self.bounds.size.height - 5;
        float width = self.bounds.size.width - 5;
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(5,5,width,height)];
    }
    return _textView;
}

您还希望将它们添加到父视图中。