子类化 UIImageView 并添加 UIControl
Posted
技术标签:
【中文标题】子类化 UIImageView 并添加 UIControl【英文标题】:Subclassing UIImageView and adding a UIControl 【发布时间】:2013-01-15 20:02:03 【问题描述】:我正在尝试对 UIImageView 进行子类化以向其添加 UIControl,以便我知道它何时被选中:
-(id)initWithSize:(CGSize)size OffImage:(UIImage *)offImage onImage:(UIImage *)onImage
if (self)
[self setTranslatesAutoresizingMaskIntoConstraints:NO];
self.userInteractionEnabled = TRUE;
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[self(80)]"
options:0
metrics:@@"WIDTH" : [NSNumber numberWithFloat:size.width]
views:NSDictionaryOfVariableBindings(self)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[self(90)]"
options:0
metrics:@@"HEIGHT" : [NSNumber numberWithFloat:size.height]
views:NSDictionaryOfVariableBindings(self)]];
self.offImage = offImage;
self.onImage = onImage;
self.selected = FALSE;
UIControl *control = [[UIControl alloc] init];
[control setTranslatesAutoresizingMaskIntoConstraints:NO];
self.control = control;
[self addSubview:control];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[control]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(control)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[control]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(control)]];
return self;
当我尝试添加约束以使 UIControl 与子类 UIImageView 的大小相同时,我收到一条错误消息,提示 self.control 没有超级视图:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format:
Unable to interpret '|' character, because the related view doesn't have a superview
H:|[control]|
^'
如果我通过创建 UIImageView 来做同样类型的事情,然后创建 UIControl 和 [imageView addsubview:control]
,它就可以正常工作。为什么当我尝试将相同的代码添加到init
方法时它会崩溃?
【问题讨论】:
【参考方案1】:您是如何创建 imageView 子类对象的?在这段代码中没有[Super init..]
【讨论】:
呸,就是这样,谢谢!我忘了self = [super init]
。现在我觉得很傻。以上是关于子类化 UIImageView 并添加 UIControl的主要内容,如果未能解决你的问题,请参考以下文章