UITableViewCell 中的复选框图像切换 [英] Checkbox image toggle in UITableViewCell

查看:35
本文介绍了UITableViewCell 中的复选框图像切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些指导来创建一个在左侧有一个可以切换的图像的 UITableViewCell.图像应该是可点击的并充当切换(复选框).

I need some guidance on creating a UITableViewCell that has an image on the left which can be toggled. The image should be tappable and act as a toggle (checkbox).

我正在努力的部分是:

  1. 如何检测图像上的点击并以与 didSelectRowAtIndexPath 不同的方式处理这些点击?
  2. 如何在不执行 [tableView reloadData] 的情况下更改图像?
  1. How do I detect taps on the image and handle those differently to didSelectRowAtIndexPath?
  2. How do I change the image without performing a [tableView reloadData]?

推荐答案

其实很简单.

只需创建一个 UIControl 的新子类并将其全部放入其中(无需单独的控制器.)我们称之为 ToggleImageControl.

Just create a new subclass of UIControl and put it all in there (no need for a separate controller.) Let's call it ToggleImageControl.

@interface ToggleImageControl : UIControl
{
   BOOL selected;
   UIImageView *imageView;
   UIImage *normalImage;
   UIImage *selectedImage;
}

为每个单元格创建一个 ToggleImageControl,并添加到合适的位置.

Create a ToggleImageControl for each cell, and add it at the appropriate position.

ToggleImageControl *toggleControl = [[ToggleImageControl alloc] initWithFrame: <frame>];
toggleControl.tag = indexPath.row;  // for reference in notifications.
[cell.contentView addSubview: toggleControl];

添加一个 UIImageView 来包含图像.为触摸事件添加目标.

Add a UIImageView to contain the image. Add a target for the touch event.

- (void) viewDidLoad
{
   normalImage = [UIImage imageNamed: @"normal.png"];
   selectedImage = [UIImage imageNamed: @"selected.png"];
   imageView = [[UIImageView alloc] initWithImage: normalImage];
   // set imageView frame
   [self.view addSubview: imageView];

[self addTarget: self action: @selector(toggleImage) forControlEvents: UIControlEventTouchUpInside];

}

设置UIImageView的image属性来更新图片;这将触发重绘而不会产生副作用.

Set the UIImageView's image property to update the image; that will trigger the redraw without side-effects.

- (void) toggleImage
{
   selected = !selected;
   imageView.image = (selected ? selectedImage : normalImage); 

   // Use NSNotification or other method to notify data model about state change.
   // Notification example:
   NSDictionary *dict = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: self.tag forKey: @"CellCheckToggled"];
   [[NSNotificationCenter defaultCenter] postNotificationName: @"CellCheckToggled" object: self userInfo: dict];

}

您显然需要按摩一些东西.您可能希望传入两个图像名称以使其更可重用,而且我还建议从对象外部指定通知名称字符串(假设您使用的是通知方法.)

You will obviously need to massage some stuff. You probably want to pass in the two image names to make it more reusable, and also I'd recommend specifying the notification name string from outside the object as well (assuming you are using the notification method.)

这篇关于UITableViewCell 中的复选框图像切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆