响应来自scrollview ios5内的一组UIImageViews的事件

时间:2012-06-06 16:57:22

标签: ipad ios5 uiview uiimageview

对于我的iPad应用程序,我正在以编程方式创建我在屏幕上显示的几个UIImage视图。代码看起来基本上是这样的:

for(ModelObject *model in ModelsList){
    //create a UIImage view from the model object
    UIImageView *icon = [[UIImageView alloc] initWithFrame:model.icon_frame];
    icon.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:model.icon_path ofType:@"png"]];

     //add the imageview to a mutable array to keep track of them
    [myImageViews addObject:icon];

    // add the view as a subview
    [self.view addSubview:icon];
}

所以现在我在屏幕上显示了一堆图标。但是我想拦截我以编程方式创建的UIImageViews中的触摸事件,以便它调用其他方法,最好使用包含发送者id的参数或我可以用来确定哪个{{{ 1}}被触动了。

实现这一目标的最佳实践方法是什么?

我是iOS的新手,所以推荐阅读也会非常感激。

1 个答案:

答案 0 :(得分:0)

请提供任何适用的反馈,因为我不知道这是否是常见的做法,甚至不是一种体面的做事方式......

所以基本上我所做的就是保存一个在视图对象和模型对象之间映射的id字典,然后我查找发送视图的id并找到合适的模型对象,(然后我将使用该模型对象加载另一个视图)

代码如下所示:

// in header
@property(nonatomic, retain) NSMutableDictionary *icons_to_models

// after creating a UIButton called icon
[icon setBackgroundImage:model.image forState:UIControlStateNormal];
[icon addTarget:self action:@selector(tappedIcon:) forControlEvents:UIControlEventTouchUpInside];
NSNumber *key = [NSNumber numberWithUnsignedInt:[icon hash]];
[icons_to_models setObject:model forKey:key];


...

//match sender to the icon that was pressed and
-(void)tappedIcon:(id)sender{
    NSNumber *key = [NSNumber numberWithUnsignedInt:[sender hash]];
    ModelObject *model = [icons_to_models objectForKey:key];
    NSLog(@"tapped on: %@", model.name);
}
相关问题