UITableView

UITableView:表视图
表视图通常用来管理一组具有相同数据结构的数据
UITableView继承于UIScrollView,所以可以滚动
表视图的每一条数据都是显示在UITableViewCell对象中
表视图可以分区显示数据,每一个分区称为一个section, 每一行称为一个row, 编号都是从0开始.

表视图的创建:
重要属性:
1.style样式: plain, group.
2.分割线样式:separatorStyle
3.分割线颜色:separatorColor
4.行高:rowHeight

一个tableView里面可以有多个重用池
po调试的时候,若内容显示为空,则这个方法一定没有初始化
解决问题方法:断点 po 输出NSLog 

cell自定义 放两个label 重用池
数组套字典

1.使用系统自定义的各种UITableViewCell的样式

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* indentifier = @"cell";
    MyTableCell* cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        
        cell = [[[MyTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier]autorelease];
    }
    cell.textLabel.text = [_data objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = @"detail";
    cell.imageView.image = [UIImage imageNamed:@"checkmark.png"];
    return cell;
}

使用UITableViewCellStyleDefault的效果:


使用UITableViewCellStyleValue1的效果:



使用UITableViewCellStyleValue2的效果:


在UITableViewCell内默认是有contentview和accessoryView这两个subview的,contentview中的subview根据不同的cell的style会使用不同的布局。contentview和其中的默认subview会根据cell的编辑状态出现的控件自动缩进,自定义cell时可以把自定义控件添加在contentview中,也可以直接添加到cell中。


2.设置UITableViewCell的属性

      //cell的右边辅助按钮的样式
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    //自定义cell右边的辅助按钮
    cell.accessoryView = nil;
    //自定义cell的背景
    cell.backgroundView = nil;
    //设置cell的contentview中的detail的文字内容
    cell.detailTextLabel.text = @"";
    //查看cell当前的编辑模式
    int style = cell.editingStyle;
    //设置当cell进入编辑模式时的辅助按钮样式
    cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //自定义cell进入编辑模式后辅助按钮
    cell.editingAccessoryView = nil;
    //获取cell的缩进级别
    int level = cell.indentationLevel;
    //获取cell的缩进宽度
    float width = cell.indentationWidth;
    //设置cell被选中时的背景
    cell.selectedBackgroundView = nil;
    //设置cell的选中状态样式
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    //设置cell的contentview中的textlabel文字内容
    cell.textLabel.text = @"";


3.自定义的UITableViewCell重写父类的方法

//初始化uitableviewcell后,自定义cell添加subview
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

//当cell被选中时,uitableview内部会自动调用该方法,重写该方法可以在cell被选中时做一些额外的操作
- (void)setSelected:(BOOL)selected animated:(BOOL)animated

//当cell处于高亮状态时,uitableview内部会自动调用该方法,重写该方法可以在cell处于高亮时做一些额外操作
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated

//重写layoutsubviews方法,为了查看当cell改变编辑状态时,有什么subview
-(void)layoutSubviews{

    [super layoutSubviews];
    NSArray* subs = self.subviews;
    for (UIView* sub in subs) {
        NSLog(@"view:%@",sub);
    }
}

当进入删除编辑模式时,cell的subview有一个叫UITableViewCellDeleteConfirmationControl的subview,这代表删除按钮。可以修改该view达到修改删除按钮的位置,大小等属性。

当进入移动编辑模式时,cell的subview有一个叫UITableViewCellReorderControl的subview,这个代表移动按钮。可以修改该view达到修改移动按钮的位置,大小等属性。

当进入插入编辑模式时,cell的subview有一个叫UITableViewCellEditControl的subview,这个代表添加按钮。可以修改该view达到修改添加按钮的位置,大小等属性。


//当cell的状态变为编辑时,uitableview内部会自动调用该方法,重写该方法可以改变cell的布局
-(void)willTransitionToState:(UITableViewCellStateMask)state{
    [super willTransitionToState:state];
}
//当cell的状态变为编辑时,uitableview内部会自动调用该方法,重写该方法可以改变cell的布局
-(void)didTransitionToState:(UITableViewCellStateMask)state{
    [super didTransitionToState:state];
    
    //滑动出现的删除按钮state是2的,编辑状态下的删除按钮state是3的
    if (state == UITableViewCellStateShowingDeleteConfirmationMask||state==3) {
        for (UIView *subview in self.subviews) {
            //cell的subview为UITableViewCellDeleteConfirmationControl时,代表是删除按钮
            if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"]) {
                
                UIView *deleteButtonView = subview;
                CGRect f = deleteButtonView.frame;
                f.origin.x -= 50;
                deleteButtonView.frame = f;            }
        }
    }
    //插入和移动的编辑状态state都是1
    else if(state==UITableViewCellStateShowingEditControlMask){
        for (UIView *subview in self.subviews) {
            NSString* type = @"";
            //判断如果cell当前是插入模式,则寻找UITableViewCellEditControl的subview,代表添加按钮
            if (self.editingStyle==UITableViewCellEditingStyleInsert) {
                type = @"UITableViewCellEditControl";
            }
            //否则寻找UITableViewCellReorderControl的subview,代表移动按钮
            else type = @"UITableViewCellReorderControl";
            if ([NSStringFromClass([subview class]) isEqualToString:type]) {
                
                UIView *deleteButtonView = [subview.subviews objectAtIndex:0];
                CGRect f = deleteButtonView.frame;
                f.origin.x -= 50;
                deleteButtonView.frame = f; 
            }
        }

    }
}


4.UITableViewCell自定义背景颜色

方法1:

通过修改contentview的backgroundcolor


方法2:

创建一个uiview,设置它的backgroundcolor后再添加到cell里


方法3:

通过在- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath的回调中设置cell的backgroundcolor



### UITableView 在 Swift 5 中的用法与常见问题解析 #### 1. **UITableView 的基本概念** `UITableView` 是 iOS 开发中最常用的控件之一,用于展示列表形式的数据。它基于委托模式(Delegate Pattern),开发者需要实现两个主要协议:`UITableViewDataSource` 和 `UITableViewDelegate`。 - `UITableViewDataSource`: 提供表格视图所需的单元格数据。 - `UITableViewDelegate`: 处理用户交互事件以及自定义单元格外观的行为。 在 Swift 5 中,`UITableView` 的核心功能保持不变,但语法更加简洁明了[^1]。 --- #### 2. **创建和配置 UITableView** ##### 设置 UITableViewDataSource 和 UITableViewDelegate ```swift class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // 初始化 UITableView 实例 tableView = UITableView(frame: self.view.bounds, style: .plain) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") // 设置代理和数据源 tableView.dataSource = self tableView.delegate = self self.view.addSubview(tableView) } // MARK: - UITableViewDataSource Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 // 返回行数 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = "Row \(indexPath.row)" return cell } } ``` 此代码展示了如何初始化一个简单的 `UITableView` 并设置其基础属性[^2]。 --- #### 3. **动态调整 UITableView 的高度** 有时我们需要根据内容自动调整 `UITableView` 的高度。可以通过监听 `contentSizeDidChangeNotification` 或者直接访问 `tableView.contentSize` 属性来实现这一点。 ```swift override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // 动态调整 tableview 高度以适应内容大小 tableView.frame.size.height = tableView.contentSize.height } ``` 这种做法适用于嵌套在其他容器中的场景,比如 `UIScrollView` 内部[^3]。 --- #### 4. **解决常见的崩溃问题** 当链接外部框架时,如果发生类似于 dyld 错误的消息(如引用[4]所示),通常是由于缺失必要的库文件或路径错误引起。确保项目中正确设置了 Framework Search Paths,并验证所有依赖项均已成功导入。 另外,在运行时尝试访问不存在的对象也可能导致异常终止。例如,试图调用未注册的 Cell Identifier 就会抛出致命错误: > Fatal error: Unexpectedly found nil while unwrapping an Optional value. 为了避免此类问题,请始终检查返回值是否为空后再继续操作。 --- #### 5. **优化用户体验的小技巧** - **滚动时隐藏导航栏**: 结合 `UIScrollViewDelegate` 协议的方法控制导航栏可见性。 ```swift func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { navigationController?.setNavigationBarHidden(true, animated: true) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { navigationController?.setNavigationBarHidden(false, animated: true) } ``` - **离线状态下禁用某些功能**: 类似于引用[1]提到的方式,可以在进入特定控制器前检测网络连接状态并相应调整界面布局。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值