很抱歉,标题听起来很混乱。但我正在尝试制作一个具有表格视图的应用程序。每行都有自己的按钮,有自己的一组点。我非常希望按钮能够向计数器添加特定数量的点数。但是,我不知道如何访问所选行的NSArray的int。这是代码:
@interface FBViewController ()
@end
@implementation FBViewController {
NSArray *tablePoints;
NSArray *tablePointLabel;
int counter;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//A table that displays the points on the buttons
tablePointLabel = [NSArray arrayWithObjects:
@"10",
@"10",
@"10",
@"20",
@"20",
@"20",
@"30",
@"30",
@"50",
@"70",
@"100",
@"300",
@"300",
nil];
//table of ints (points)
tablePoints = [NSArray arrayWithObjects:
@10,
@10,
@10,
@20,
@20,
@20,
@30,
@30,
@50,
@70,
@100,
@300,
@300,
nil];
counter = 0;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"FBCell";
FBCell *cell = (FBCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FBCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
UIButton *pointButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
pointButton.frame = CGRectMake(250.0f, 5.0f, 75.0f, 30.0f);
[pointButton setBackgroundColor:[UIColor greenColor]];
[pointButton setTitle:[tablePointLabel objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell addSubview:pointButton];
[pointButton addTarget:self
action:@selector(addPoint:)
forControlEvents:UIControlEventTouchUpInside];
return cell;
}
-(IBAction)addPoint:(id)sender {
counter + [tablePoints objectAtIndex:indexPath.row] = counter;
**//This is where I have an issue. indexPath.row does not work for int arrays. what do i do???**
}
答案 0 :(得分:0)
NSArray包含对象,而不是值。在您的情况下,它包含NSNumber对象,而NSNumber对象又保存值。
使用indexPath.row获取NSNumber,然后获取值。
NSNumber *numberObject = [tablePoints objectAtIndex:myIndex];
int myInt = [numberObject intValue]; // NSNumber covers a range of different types of values
一个问题是你在哪里获得indexPath.row并且在那时它是有效的。
答案 1 :(得分:0)
很多方法可以改善这一点(包括rmaddy提供的建议)
我的建议不是实例化一个uibutton(我猜测是等于每个表行的高度/宽度,是实现
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//increments counte
counter += [tablePoints[indexPath.row] intValue];
}
此外,对于行标签,只需坚持uilabel,并为(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath,根据数组值设置标签。实际上,您甚至不需要声明两个相同的数组,只需重新调整相同的数组。