同时使用多个UITableView

1.xib\storyboard中给2个tableView设置constraints(等宽)
方法 :
①设置mainTableView的上\下\左\三部分的约束为0;subTableView上\下\右\的约束为0;
②同时选中mainTableView和subTableView,设置为等宽和等高;
 
2.代理和数据源设置
mainTableView和subTableView的代理和数据源都为该控制器
 
3.点击如何处理
示例情景:一个模型A给tableView提供数据,且有个属性为数组,数组里面存放着子模型B。mainTableView展示模型A的数据;subTableView展示模型B的数据。
方法:
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.mainTableView) {  // 主表
        return [存放主表的数组的个数];
    } else // 从表
        return [存放从表的数组的个数];
    }
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    if (tableView == self.mainTableView) {  // 主表
 
                 // 展示主表cell.textLable.text
 
        // 根据数组属性是否有值,判断是否添加箭头样式(提醒用户该主表存在从表数据)
        if (subdata.count) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    } else // 从表
         // 展示从表cell.textLable.text,需要注意的是需要在cell点击事件里面标记当前选中的cell的下标,设置为属性。因为从表里面展示的数据就是根据主表所选中的row实现的。
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.mainTableView) {
        // 被点击的数据
        self.selectedMainRow = indexPath.row;
       
        // 刷新右边的数据(必须刷新)
        [self.subTableView reloadData];
    }
}
 
4.2个tableView在xib\storyboard中缩小的原因(不仅仅是tableView,其他控件往xib的View中添加也可能会出现)
 
分析为什么把xib中这2个tableView添加到控制器view上面,会消失:如下图
 
 
原因:storyboard或者xib中自动勾选了自动布局的,如果把xib中的tableView加载到父控件的view上面,如果父控件的view的尺寸缩小,那么xib中的tableView的大小也会跟随者父控件的尺寸缩小而缩小,并且最后会缩小为0。
导致的结果:
①导致view中不会显示tableView
②tableView消失之后,不会调用tableView的代理方法
解决办法:
- (void)awakeFromNib {
    // autoresizingMask,该属性默认为none。如果xib/storyboard中设置了autolayout,那么该属性就会被打开。需要我们自己手动关闭。
    self.autoresizingMask = UIViewAutoresizingNone;
}
posted @ 2016-02-17 13:17  Kingdev  阅读(1268)  评论(0编辑  收藏  举报