【问题标题】:My UIImageView doesn't get all the methods of my subclassed UIImageView我的 UIImageView 没有得到我的子类 UIImageView 的所有方法
【发布时间】:2010-01-26 22:14:46
【问题描述】:

我使用以下方法创建了 UIImageView 的子类(称为 MyPicture):

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
    }
    return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"-- I AM TOUCHED --");
}

//…

当我使用带有 MyPicture 类的 InterfaceBuilder 创建 UIImageView 时,一切正常,控制台写道:“我被触摸了”。但仅当我在 IB 中激活用户交互时。

但是当我以编程方式创建 UIImageView 时,它确实有效。 在 ViewController.h 中:

MyButton * foo;

在 ViewController.m 中:

- (void)viewDidLoad {
    flo = [[UIImageView alloc]initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];
    foo.userInteractionEnabled = YES;
    foo.image = [UIImage imageNamed:@"Picture 1.png"];
    [self.view addSubview:foo];
    [super viewDidLoad];
}

我可以看到图片,所以它必须是我的 UIImageView 子类。但是为什么他没有检测到触摸呢?

【问题讨论】:

    标签: iphone objective-c xcode


    【解决方案1】:

    我不明白为什么它必须是你的子类。看到图片就意味着它是一个 UIImageView。这正是它的本质(不是子类):

    foo = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];
    

    您正在初始化 UIImageView,而不是您的子类。尝试将该行更改为:

    foo = [[MyPicture alloc] initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];
    

    编辑:此外,由于您在子类 'initWithFrame:' 方法中设置了 userInteractionEnabled = YES,因此没有理由在此行中再次执行此操作:

    foo.userInteractionEnabled = YES;
    

    【讨论】:

    • 谢谢,现在可以了。我用 [MyPicture alloc] 尝试过,但应用程序崩溃了。但正如我所说,现在它可以工作了。
    【解决方案2】:

    当您继承 UIImageView 时,应用程序可以通过几种不同的方式调用对象。在 Interface Builder 中创建的 UIImageViews 被预编译并加载到内存中,而无需调用 -(id)init 方法。相反,它们会在 nib 的内容加载到内存后调用- (void)awakeFromNib

    确保您的类标识设置为您的子类,并在您的子类的 awakeFromNib 方法中设置 userInteractionEnabled。这将允许您在不绑定的情况下设置用户交互。

    要以编程方式完全加载 UIImageView,请确保从正确的类进行分配。您的代码是从 UIImageView 超类调用的。

    - (void)viewDidLoad {
        foo = [[MyImageView alloc] initWithFrame:CGRectMake(0.0, 45.0, 324, 52.0)];
        foo.image = [UIImage imageNamed:@"Picture 1.png"];
        [self.view addSubview:foo];
        [super viewDidLoad];
    }
    

    这将从您的子类而不是超类调用- (id)initWithFrame 并执行您的自定义代码。这也会将- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 调用发送到您的子类而不是超类。

    【讨论】:

      猜你喜欢
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多