对UIImageView进行子类化并添加UIControl

时间:2013-01-15 20:02:03

标签: ios objective-c uiimageview autolayout nslayoutconstraint

我正在尝试将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没有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]| 
            ^'

如果我通过创建UIImageView来做同样类型的事情,那么创建一个UIControl和[imageView addsubview:control],它就可以了。当我尝试将相同的代码添加到init方法时,为什么会崩溃?

1 个答案:

答案 0 :(得分:2)

您是如何创建imageView子类对象的?在这段代码中没有[Super init ..]