[英]How to access an int from a NSArray on the selected row?
抱歉,標題聽起來令人困惑。 但是我正在嘗試制作一個具有表視圖的應用程序。 每行都有自己的按鈕,並帶有自己的一組點。 我非常希望按鈕將特定數量的點添加到計數器。 但是,我不知道如何訪問所選行的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???**
}
NSArray保存對象,而不保存值。 在您的情況下,它包含NSNumber對象,這些對象又包含值。
使用indexPath.row獲取NSNumber,然后獲取值。
NSNumber *numberObject = [tablePoints objectAtIndex:myIndex];
int myInt = [numberObject intValue]; // NSNumber covers a range of different types of values
一個問題是,您在哪里獲取indexPath.row,並且在那時是否有效。
許多改善方法(包括rmaddy提供的建議)
我的建議是不要實例化uibutton(我猜它等於每個表行的高度/寬度,而是實現
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//increments counte
counter += [tablePoints[indexPath.row] intValue];
}
此外,對於行標簽,只需粘貼uilabel,對於(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath,請根據數組值設置標簽。 實際上,您甚至不需要聲明兩個相同的數組,只需重新使用相同的數組即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.