【问题标题】:UITableViewController not being filled with NSMutableArrayUITableViewController 没有被 NSMutableArray 填充
【发布时间】:2023-03-29 02:20:01
【问题描述】:

我有一个表格视图控制器,FavoritesTableViewController,它有一个可变数组“citiesArray”。当按下城市按钮时,它会调用一个将对象添加到可变数组的方法。

[self.citiesArray addObject:@"New York"];

然后它会记录 self.citiesArray 的计数以及数组本身,并且似乎工作正常,这意味着它成功地将字符串“New York”添加到数组中。所以现在我有一个填充的可变数组并想用它填充表格视图。

这是我的代码,似乎不起作用。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
       UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
       if (cell==nil) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
       } 
       cell.textLabel.text=[self.citiesArray objectAtIndex:indexPath.row];
       return cell;
}

之后我尝试重新加载我的表格视图,但仍然无法正常工作。关于问题是什么的任何想法? 谢谢

【问题讨论】:

  • 别忘了检查表视图委托。
  • @pawan,委托与此问题无关。如果 OP 没有设置数据源可能是问题,但委托方法与获取数据无关。
  • @rdelmar 我的错,我错误地写了委托,它应该是数据源。

标签: ios objective-c arrays nsmutablearray uitableview


【解决方案1】:

你必须添加方法来返回表中有多少行:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.citiesArray.count;
}

【讨论】:

    【解决方案2】:

    实现方法:

    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
        return 1;
    }
    
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{  
        return self.citiesArray.count;
    }
    

    当然,如果您还没有设置表的datasourcedelegate 属性,您应该这样做,例如在ViewDidLoad 方法中:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        //....Your code....
    
        table.delegate = self;
        table.datasource = self;
    }
    

    【讨论】:

    • 与@Greg 发布的相同。
    • numberOfSectionsInTableView: 如果您只有一个部分,则为可选。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多