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

查看:122
本文介绍了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. 如何在不执行[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,并将其添加到适当的位置。 / p>

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天全站免登陆