我为每个视单元创建了自定义按钮(每个单元 1 个)。滚动 UITableView 时,一些 viewcells 有 2 个按钮,这不是故意的。我看不到我的方式中的错误。
请帮忙!
图片:http ://s18.postimg.org/v7djg84ah/buttons_App.png
标题:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource>
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section;
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
-(void)checkboxSelected:(id)sender;
@end
执行
#import "ViewController.h"
#define sectionCount 1
#define itemSection 0
@interface ViewController ()
{
NSArray *items;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
items = @[@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2",@"itemdd", @"item2"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return sectionCount;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch(section)
{
case itemSection:
{
return [items count];
}
default:
return 0;
}
}
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
switch (section)
{
case itemSection:
return @"Items";
default:
return @"woot";
}
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"itemCell"];
switch(indexPath.section)
{
case itemSection:
cell.textLabel.text = items[indexPath.row];
break;
default:
cell.textLabel.text=@"Unknown";
}
NSInteger x,y;
x =cell.frame.origin.x +100; y = cell.frame.origin.y + 10;
UIButton *checkbox;
checkbox = [[UIButton alloc] initWithFrame:(CGRectMake(x,y,20,20))];
[checkbox setBackgroundImage:[UIImage imageNamed:@"notSelectedButton.png"]forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"checkedButton.png"]forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"uncheckedButton.png"]forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted = YES;
[checkbox addTarget:self action:@selector(checkboxSelected:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:checkbox];
return cell;
}
-(void)checkboxSelected:(id)sender
{
bool selected = [(UIButton *)sender isSelected];
if (selected)
{
[(UIButton *)sender setSelected:false];
}
else
{
[(UIButton *)sender setSelected:true];
}
}
@end