I’m trying to subclass the UIImageView to add a UIControl to it so i know when it is selected:
-(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;
}
When i try to add the constraints to make the UIControl the same size as the subclassed UIImageView, i get an error saying that self.control does not have a superview:
*** 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]|
^'
If i do this same type of thing by creating a UIImageView, then create a UIControl and [imageView addsubview:control], it works just fine. Why is it crashing when i try to add the same code to the init method?
How did you create your imageView Subclass object? In this code there is no [Super init..]