2016-10-18 42 views
-2

我是新來的應用程序開發。在我的應用程序中,當我點擊我的表格視圖單元格時,單元格被選中,並且不管我是單擊圖像還是單元格,都會觸發該方法。我希望在點擊圖片時選擇圖片,而不是單元格。提前致謝。如何通過觸摸tableviewcell選擇圖像

+0

你可以添加一個自定義按鈕到你的tableviewcell並給它的動作 – Arun

+0

顯示你的嘗試代碼 –

+0

請在SA中提問時更具體。向我們展示一些代碼你試過的東西 – Arun

回答

0

在圖像視圖中添加UITapGestureRecognizer,如果您不想單元格選擇,則關閉表格視圖單元格選擇。在圖像上點擊功能做你想要的。

0

在您的cellForRowAtIndexPath方法中,添加一個自定義UIButton並將該圖像指定爲該按鈕的背景圖像。然後添加目標按鈕和手柄的按鈕目標方法

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"]; 


     UIButton *imageButton = [[UIButton alloc] initWithFrame:<Give the frame you want>]; 
     [imageButton setBackgroundImage:<your image> forState:UIControlStateNormal]; 
     [imageButton addTarget:self action:@selector(imageButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
     [cell addSubview:imageButton]; 

    } 

    return cell; 
} 

在這裏,最好的方法是創建一個自定義UITableViewCell具有imageButton作爲一個實例變量,而不是內部cellForRowAtIndexPath方法創建它的內部代碼。現在在imageButtonClicked方法,以便它放在你想要的位置

-(void)imageButtonClicked:(UIButton *)sender { 

    UIImage *image = sender.currentBackgroundImage; 

    //Do the logic what you want here 

} 

請給按鈕的框架。

我還沒有試過這段代碼。如果sender.currentBackgroundImage沒有給你圖像,那麼創建一個從UIButton擴展的自定義按鈕。自定義按鈕應該有一個UIImage變量作爲實例變量。將變量分配給初始化時所需的圖像(在cellForRowAtIndexPath方法中)。然後你可以訪問按鈕目標方法中的圖像

+1

我會很好,如果'UIButton * imageButton = [[UIButton alloc] .......... forControlEvents:UIControlEventTouchUpInside]; [cell addSubview:imageButton];'移動到自定義的UITableViewCell類。每次調用addSubview:代價都很高。 – byJeevan

+0

是的,我同意你的意見。我這樣做是爲了向他展示它是如何完成的。最好的方法是創建一個自定義的UITableViewCell類 – Arun

+0

如何用UITableViewCell Class做到這一點。建議我。 –