我通过以下代码创建了一个名为ToggleImageControl的UIControl子类(参考以下帖子Checkbox image toggle in UITableViewCell)
@interface ToggleImageControl : UIControl
{
BOOL photoIsStarred;
UIImageView *imageView;
UIImage *normalImage;
UIImage *selectedImage;
}
@property (nonatomic, assign) BOOL photoIsStarred;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) UIImage *normalImage;
@property (nonatomic, retain) UIImage *selectedImage;
- (void) toggleImage;
@end
@implementation ToggleImageControl
@synthesize photoIsStarred, imageView, normalImage,selectedImage;
- (id)initWithFrame:(CGRect)frame
{
NSLog(@"in inti with frame method");
self.normalImage = [UIImage imageNamed: @"blank_star.png"];
self.selectedImage = [UIImage imageNamed: @"star.png"];
self.imageView = [[UIImageView alloc] initWithImage: normalImage];
// set imageView frame
[self addSubview: imageView];
[self addTarget: self action: @selector(toggleImage) forControlEvents: UIControlEventTouchDown];
return self;
}
- (void) toggleImage
{
NSLog(@"image toggled");
self.photoIsStarred = !photoIsStarred;
self.imageView.image = (photoIsStarred ? selectedImage : normalImage);
}
@end
我尝试在表格单元格中创建ToggleImageControl的实例,但无法显示“正常图像”。我的实现中是否缺少某些内容?
//In a UItableview cell
ToggleImageControl *toggleControl = [[ToggleImageControl alloc]initWithFrame:CGRectMake(670, 10,80, 80)];
[cell.contentView addSubview:toggleControl];
答案 0 :(得分:5)
请务必使用[super initWithFrame:frame]
方法拨打initWithFrame:
。
e.x。
self = [super initWithFrame:frame];
if (self) {
// Initialization
}
return self;