我创建了以下子类来做一些自定义绘图:
// DocumentIconView.h
@interface DocumentIconView : UIView
{
UIImageView *documentIconView;
CloseHandle *closeHandle;
UILabel *filenameLabel;
}
@property (nonatomic, strong) UIImageView *documentIconView;
@property (nonatomic, strong) CloseHandle *closeHandle;
@property (nonatomic, strong) UILabel *filenameLabel;
+ (DocumentIconView *)documentIconWithFrame:(CGRect)viewFrame
previewImage:(UIImage *)previewImage
title:(NSString *)title;
这大部分都适用(我可以实例化对象,并进行自定义绘图),但是,我无法从其他类访问它的某些属性。
DocumentIconView *iconView = [DocumentIconView documentIconWithFrame:frame
previewImage:[UIImage imageNamed:@"GenericDocumentIcon.png"]
title:[NSString stringWithFormat:@"test"]];
iconView.backgroundColor = [UIColor lightGrayColor]; // this works
iconView.filenameLabel.backgroundColor = [UIColor darkGrayColor]; // this does not work - no error message
[documentsView addSubview:iconView];
我可以读写第一级属性,但不能深入钻取;尝试读取属性时,返回的值为(null)
我在子类化方面相当新,所以我觉得我错过了一些非常明显的东西。任何帮助将不胜感激。
编辑:实例化相关视图的方法:
+ (DocumentIconView *)documentIconWithFrame:(CGRect)viewFrame
previewImage:(UIImage *)previewImage
title:(NSString *)title
{
DocumentIconView *view = [[DocumentIconView alloc] initWithFrame:viewFrame];
// Close handle's size is assigned here
CGSize closeHandleSize = CGSizeMake(27, 27);
// The document preview image's frame is calculated by shrinking it by the close handle's size
CGRect documentPreviewFrame = CGRectMake(closeHandleSize.width / 2,
closeHandleSize.height / 2,
viewFrame.size.width - closeHandleSize.width,
viewFrame.size.height - closeHandleSize.height - 20); // 20 points is the filenameLabel's height
UIImageView *documentPreviewView = [[UIImageView alloc] initWithFrame:documentPreviewFrame];
documentPreviewView.contentMode = UIViewContentModeScaleAspectFit;
documentPreviewView.backgroundColor = [UIColor clearColor];
documentPreviewView.image = previewImage;
[view addSubview:documentPreviewView];
CGRect closeHandleFrame = CGRectMake(0, 0, closeHandleSize.width, closeHandleSize.height);
CloseHandle *closeHandleView = [[CloseHandle alloc] initWithFrame:closeHandleFrame];
closeHandleView.alpha = 0.0;
closeHandleView.tag = kCloseHandleTag;
[view addSubview:closeHandleView];
CGRect filenameFrame = CGRectMake(0,
viewFrame.size.height - 20,
viewFrame.size.width,
20);
UILabel *filenameLabel = [[UILabel alloc] initWithFrame:filenameFrame];
filenameLabel.backgroundColor = [UIColor clearColor];
filenameLabel.text = title;
filenameLabel.font = [UIFont boldSystemFontOfSize:17];
filenameLabel.textColor = [UIColor whiteColor];
filenameLabel.textAlignment = UITextAlignmentCenter;
[view addSubview:filenameLabel];
view.tag = kDocumentIconTag;
return view;
}
答案 0 :(得分:2)
在documentIconWithFrame:...
方法中,您使用的是您要添加到视图中的局部变量(filenameLabel
)。这意味着您的实例变量从未实例化,始终为nil
。
只需改变一下:
UILabel *filenameLabel = [[UILabel alloc] initWithFrame:filenameFrame];
到此:
filenameLabel = [[UILabel alloc] initWithFrame:filenameFrame];
和其他实例变量相同。