编辑TableView代码时出现问题

时间:2011-03-25 02:30:48

标签: iphone objective-c

通过滑动并单击“删除”,我创建了一个包含可编辑数组的表(可以删除行)。但是,我试图让它点击导航栏中的编辑按钮,每个单元格旁边都会出现红色减号。

我正在使用我书中的代码,但tableView变量无效。我无法弄清楚它是如何在书中起作用的,而不是在我的项目中。

我认为这是因为本书的类是UITableViewController的子类,而我的是一个带有UITableViewController对象的UIViewController。那我怎么能让它发挥作用呢?

我的界面文件中也有一个用于tableView的IBOutlet。

以下是相关代码:

#import "RoutineTableViewController.h"
#import "AlertPrompt.h"

@implementation RoutineTableViewController

@synthesize myArray;
@synthesize myData;

- (void)viewDidLoad
{
    myArray = [[NSMutableArray alloc] init]; 
    myData = [[NSMutableArray arrayWithContentsOfFile:@"mydata"] retain]; 

    if (myData == nil)
    {
        myData = [NSMutableArray array];  
    }

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

-(IBAction)toggleEdit:(id)sender
{
    [self.tableView setEditing: !=self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

2 个答案:

答案 0 :(得分:1)

您需要将每个UITableViewCell的editingStyle设置为UITableViewCellEditingStyleDelete。这应该在表视图的委托中创建单元格时完成(tableView:cellForRowAtIndexPath :)

答案 1 :(得分:0)

这可能看起来像我假设你是一个全新手,但相信我,很多人都忘记了这一点(我不是说我也是专家),但是你应该检查你的编辑按钮是否连接到Interface Builder中对应的IBOutlet

编辑:忘了问,你的按钮是IBOutlet(IB元素)吗?或者是以编程方式创建的?如果第二个为真,则不应将IBActions用于以编程方式创建的对象(因此Interface Builder Action = IBAction)