我正在尝试对 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
方法时它会崩溃?