2012-06-06 48 views
0

對於我的iPad應用程序,我以編程方式創建了幾個UIImage視圖,並將其顯示在屏幕上。代碼看起來基本上是這樣的:響應滾動視圖內的UIImageView數組中的事件ios5

 
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或一些其他可用於確定觸摸哪些區分信息的參數。

完成此操作的最佳實踐方法是什麼?

我是iOS新手,所以推薦閱讀也將不勝感激。

回答

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); 
} 
相關問題