【问题标题】:Subclassing UIImageView and adding a UIControl子类化 UIImageView 并添加 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 方法时它会崩溃?

【问题讨论】:

    标签: ios objective-c uiimageview autolayout nslayoutconstraint


    【解决方案1】:

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

    【讨论】:

    • 呸,就是这样,谢谢!我忘了self = [super init]。现在我觉得很傻。
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多