0

所以我想做的是为我的应用程序创建一个记事本样式。我只想让它像苹果现有的记事本一样工作在 UITableView 中。

我已经有了 UITableView 和一切设置我只需要知道如何运行这个动作

-(IBAction)noteAdd:(id)sender{ }

然后,当您单击该按钮时,它会执行我上面描述的操作。

我该怎么做呢?我有点失落。

顺便说一句,这就是我将 TableView 添加到场景中的方式。

//tableview datasource delegate methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return cameraArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath{
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];


if(cell == nil){
    cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:@"Cell"];
}

NSEnumerator *enumerator = [cameraArray objectEnumerator];
id anObject;
NSString *cellName = nil;
while (anObject = [enumerator nextObject]) {
   cellName = anObject;
}
//static NSString *cellName = [cameraArray.objectAtIndex];
cell.textLabel.text = [NSString stringWithFormat:cellName];
return cell;

}
4

1 回答 1

1

UITableView

- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

所以你会做类似的事情

-(IBAction) noteAdd:(id)sender
{
    NSIndexPath *newCellPath = [NSIndexPath indexPathForRow:cameraArray.count 
                                                  inSection:0];

    // I'm assuming cameraArray is declared mutable.
    [cameraArray addObject:@"New item"];

    [self.tableView insertRowsAtIndexPaths:@[newCellPath]
                          withRowAnimation:UITableViewRowAnimationFade];
}

当我在这里时,对您的代码有一些评论:

我很确定这段代码:

NSEnumerator *enumerator = [cameraArray objectEnumerator];
id anObject;
NSString *cellName = nil;
while (anObject = [enumerator nextObject]) {
   cellName = anObject;
}

是获取数组中最后一个字符串的一种相当迂回的方法。您可以使用cameraArray.lastObject. 但我认为这也不是你想要的,我认为你正在寻找

// XCode >= 4.5:
cellName = cameraArray[indexPath.row];

// XCode < 4.5:
cellName = [cameraArray objectAtIndex:indexPath.row];

下一行:

cell.textLabel.text = [NSString stringWithFormat:cellName];

最好的情况是,这会创建一个无关的字符串。如果单元格名称中恰好有一个%,你几乎肯定会得到一个错误或一个EXC_BAD_ACCESS. 要修复该错误,您可以使用

cell.textLabel.text = [NSString stringWithFormat:@"%@", cellName];

但真的没有理由这样做。只需直接分配字符串:

cell.textLabel.text = cellName;

或者,如果您坚持要一份副本:

cell.textLabel.text = [NSString stringWithString:cellName];
// OR
cell.textLabel.text = [[cellName copy] autorelease];
// OR
于 2012-10-12T03:21:08.517 回答