ios - uitableview 对象数组作为数据源

标签 ios objective-c uitableview object nsmutablearray

我在 ios xcode 项目的 Storyboard中有一个 UITableView,

我还有一组 menuitem 对象存储在 itemarray 中:

NSMutableArray *itemarray;

这是我的menuitem.h文件

#import <Foundation/Foundation.h>
@interface menuitem : NSObject
@property (nonatomic) NSString *itemtitle;
@property (nonatomic) NSString  *itemdesc;
@property (nonatomic) int itemid;
@property (nonatomic) int itemprice;
@property (nonatomic) NSString  *itemcat;
@end

这是我的 tableviewcell.m 文件:

#import "tableviewcell.h"
#import "menuitem.h"
@interface tableviewcell ()
@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
@property (nonatomic, weak) IBOutlet UILabel *descLabel;
@property (nonatomic, weak) IBOutlet UILabel *priceLabel;


@end

@implementation tableviewcell
-(void)configureWithmenuitem:(menuitem *)item{
    NSLog(@"hello");

    self.titleLabel.text = item.itemtitle;
    self.descLabel.text = item.itemdesc;

    self.priceLabel.text = [NSString stringWithFormat:@"%.1d", item.itemprice];
}

@end

我想将 menuitem 的每个实例中的 itemtitleitemdescitemprice 获取到 3 个标签中每个 tableviewcell

最佳答案

您的 tableviewcell 是一个 View ,因此它应该只知道如何显示自己而不是显示什么。告诉 View 显示什么是 Controller 的工作(通过委托(delegate) tableView:cellForRowAtIndexPath: 方法)。

因此你应该这样做:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Id"];

      //Assuming you've stored your items in an array.
      Item *item = [items objectAtIndex:indexPath.row];

      cell.titleLabel.text = item.itemTitle;
      cell.descLabel.text = item.itemdesc;
      cell.priceLabel.text = [NSString stringWithFormat:@"%.1d", item.itemprice];
      return cell;
}

^ 上面的代码假定您有一个原型(prototype)单元格。如果不这样做,则如果单元格在出队后为 nil,则必须进行分配。

关于ios - uitableview 对象数组作为数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23948427/

相关文章:

ios - 为 ios 中的不同 View Controller 设置不同的标签栏外观

ios - 如何从 native iOS 应用程序启动 Unity 3D 应用程序

ios - 在 Xcode Workspace 中构建单个项目

ios - UIActivityIndi​​catorView 未显示在 iOS UIViewController 中

objective-c - 在 iOS6 中的单个 UIViewController 上禁用自动旋转

ios - 具有模态表单的自定义委托(delegate)不起作用

ios - 使用标签在 TableView 中检索数据的问题

ios - UITableView 底部奇怪的空白空间

ios - 具有自调整单元格的 Interface Builder 行高

ios - 无法识别超出父 View 范围的 UILabel 上的点击