我在我的视图类中编写了一个tableView,但它无法显示dataSource

时间:2016-11-05 04:12:54

标签: ios objective-c uitableview

  

导入“YBLeftView.h”

@interface YBLeftView()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UIView *myLeftView;
@property(nonatomic,strong)NSMutableArray *tableDataArray;
@property(nonatomic,strong)UITableView *tableView;
@end

//属性初始化;省略

@implementation YBLeftView

-(instancetype)init
{
    UIView *myLeftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width/3,[UIScreen mainScreen].bounds.size.height)];
    myLeftView.backgroundColor=[UIColor colorWithRed:26/256.f green:31/256.f blue:36/256.f alpha:0.7];

    //tableView
    UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 114, myLeftView.bounds.size.width, myLeftView.bounds.size.height-164) style:UITableViewStylePlain];
    [myLeftView addSubview:tableView];
    self.tableView=tableView;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    tableView.backgroundColor=[UIColor colorWithRed:26/256.f green:31/256.f blue:36/256.f alpha:0.7];
    tableView.separatorStyle=NO;
    //data
    NSMutableArray *tableDataArray=[[NSMutableArray alloc]init];
    NSArray *dataArray=@[@"首页",@"日常心理学",@"用户推荐日报",@"电影日报",@"不许无聊",@"设计日报",@"大公司日报",@"财经日报",@"互联网安全",@"开始游戏",@"音乐日报",@"动漫日报",@"体育日报"];
    self.tableDataArray=tableDataArray;
    [self.tableDataArray addObjectsFromArray:dataArray];


    return myLeftView;
}

#pragma mark - 表视图数据源

//这行正常,它记录tableDataArray.count的计数,tableView返回计数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"%lu",(unsigned long)self.tableDataArray.count);
    return self.tableDataArray.count;
}

//此行不起作用,甚至

NSLog(@"%@",_tableDataArray[indexPath.row]);

此代码。我添加了dataSource和delegate,为什么会这样?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID=@"reuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    NSLog(@"%@",_tableDataArray[indexPath.row]);
//    cell.textLabel.text=_tableDataArray[indexPath.row];
    cell.textLabel.text=@"22";
    cell.imageView.image=[UIImage imageNamed:@"Menu_Follow"];
    return cell;
}
@end

code excuted

1 个答案:

答案 0 :(得分:1)

您可以尝试使用代码在左侧视图中添加tableview,如下所示:

UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 114,myLeftView.bounds.size.width, myLeftView.bounds.size.height-164) style:UITableViewStylePlain];
    self.tableView=tableView;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [myLeftView addSubview:self.tableView];
    ...
    [self.view addSubview:myLeftView];


尝试使用代码,希望得到结果。因为在视图中添加该属性后将所有属性赋予控制器可能会导致意外结果。因此,在给出所有属性后,只需尝试在左视图中添加tableview。然后在主视图中添加左视图。
这可能会对你有所帮助 祝你好运。