UITableView和UITableViewCell常用属性和方法

表视图继承自UIScrollView,这样的继承关系使得表视图可以实现上、下滚动。
UITableViewDatasource:实例化表视图时,必须采用该方法来实现数据源的配置
UITableViewDelegate:表视图的委托方法,一般用于处理表视图的基本样式以及捕捉选中单元格选中事件

表视图的结构:

表视图由头部、尾部视图,中间有一连串的单元格视图

表视图的头部由tableHeaderView属性设置,尾部视图通过tableFooterView属性设置

分组表格由一系列的section视图组成,每一个section又包含一个连续的单元格

每个section视图也由头部视图和尾部视图,通过委托方法代理



常用属性:

第一、分割线的颜色和style:

@property(nonatomic)UITableViewCellSeparatorStyle separatorStyle;             // default is UITableViewCellSeparatorStyleSingleLine

@property(nonatomic,retain)UIColor               *separatorColor;             // default is the standard separator gray

代码:

    self.tableView.separatorColor=[UIColor yellowColor];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLineEtched;
    [self.view addSubview:self.tableView];
第二、设置背景颜色
    self.tableView.backgroundColor=[UIColor blueColor];
    UIImageView *imageView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"10179888.jpg"]]autorelease];
    self.tableView.backgroundView=imageView;
第三 、设置headerView和footerView

@property(nonatomic,retain)UIView *tableHeaderView;                           // accessory view for above row content. default is nil. not to be confused with section header

@property(nonatomic,retain)UIView *tableFooterView;  

    UIView *topheadView=[[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)] autorelease];
    topheadView.backgroundColor=[UIColor yellowColor];
    self.tableView.tableHeaderView=topheadView;
    UIView *topFootView=[[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)] autorelease];
    topFootView.backgroundColor=[UIColor redColor];
    self.tableView.tableFooterView=topFootView;

第四、设置section的title

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = [NSString stringWithFormat:@"header 第%d个section", section+1];
    return title;
} // 设置section header 的title

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    NSString *title = [NSString stringWithFormat:@"footer 第%d个section", section+1];
    return title;
}

第五、viewForFooterInSection和viewForHeaderInSection

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    headerView.backgroundColor = [UIColor cyanColor];
    return [headerView autorelease];
}
  // 设置section自定义头部视图


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectZero];
    footerView.backgroundColor = [UIColor cyanColor];
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, 200, 30)];
    tipLabel.numberOfLines = 0;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.text = [NSString stringWithFormat:@"section footer %d", section+1];
    [footerView addSubview:tipLabel];
    [tipLabel release];
    
    return [footerView autorelease];
} // 设置section自定义尾部视图

第六、设置高度

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 44;
    }return 25;
} // 设置section header的高度


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 12) {
        return 80;
    }return 50;
} // 设置section footer的高度

第七、触摸相关                         

@property(nonatomic,getter=isEditing)BOOL editing;                            // default is NO. setting is not animated.

- (void)setEditing:(BOOL)editing animated:(BOOL)animated;

@property(nonatomic)BOOL allowsSelectionNS_AVAILABLE_IOS(3_0); // default is YES. Controls whether rows can be selected when not in editing mode

第八、多点触摸相关

@property(nonatomic)BOOL allowsSelectionDuringEditing;                                    // default is NO. Controls whether rows can be selected when in editing mode

@property(nonatomic)BOOL allowsMultipleSelectionNS_AVAILABLE_IOS(5_0);                // default is NO. Controls whether multiple rows can be selected simultaneously

@property(nonatomic)BOOL allowsMultipleSelectionDuringEditingNS_AVAILABLE_IOS(5_0);  // default is NO. Controls whether multiple rows can be selected simultaneously in editing mode

第九、跟cell 相关

- (NSInteger)numberOfSections;

- (NSInteger)numberOfRowsInSection:(NSInteger)section;


常用方法:

- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;

- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animationNS_AVAILABLE_IOS(3_0);

- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSectionNS_AVAILABLE_IOS(5_0);


- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;

- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animationNS_AVAILABLE_IOS(3_0);

- (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPathNS_AVAILABLE_IOS(5_0);

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.

- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);// newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered

- (id)dequeueReusableHeaderFooterViewWithIdentifier:(NSString *)identifierNS_AVAILABLE_IOS(6_0); // like dequeueReusableCellWithIdentifier:, but for headers/footers

第十、UITableViewDelegate相关的方法

// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPathNS_AVAILABLE_IOS(3_0);

// Called after the user changes the selection.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath;

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC=[[[DetailViewController alloc] init] autorelease];
    [self.navigationController pushViewController:detailVC animated:YES];
    NSLog(@"clicked");
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;

sampleCode:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  if(indexPath.row==1)
  {
      return 100;
  }else
  {
      return 50;
  }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60;
}

 第十一、设置单元格是否能编辑

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath

{

    if (indexPath.row == 0) {

        return NO;

    }

    return YES;

}

 第十二、 用户编辑时调用


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // 1.delete data 2.delete from table

        [_fontsArray removeObjectAtIndex:indexPath.row];

        [self.tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationLeft];

    }

    else if (editingStyle == UITableViewCellEditingStyleInsert) {

        NSString *newFont = [NSString stringWithFormat:@"New Font %d"count];

        [_fontsArray insertObject:newFont atIndex:indexPath.row+1];

        NSIndexPath *_indexPath = [NSIndexPath indexPathForRow:indexPath.row+1inSection:0];

        [self.tableView insertRowsAtIndexPaths:@[_indexPath]withRowAnimation:UITableViewRowAnimationMiddle];

        count++;

    }   

}

第十三、 移动结束调用

// Override to support rearranging the table view.

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath*)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath

{

    for (id text in _fontsArray) {

        NSLog(@"font : %@", text);

    }

    NSLog(@"___________");

    

    NSString *text = [[_fontsArray objectAtIndex:fromIndexPath.rowretain]; // 2

    [_fontsArray removeObject:text]; // 0

    [_fontsArray insertObject:text atIndex:toIndexPath.row];

    [text release];

    

    for (id text in _fontsArray) {

        NSLog(@"change font : %@", text);

    }

}

第十四、指定单元格移动


// Override to support conditional rearranging of the table view.

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath*)indexPath

{

    return YES;

//

第十五、设置单元格编辑的样式

#pragma mark - Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (indexPath.row == 0) {

        return UITableViewCellEditingStyleNone;

    }else if (indexPath.row == 1) {

        return UITableViewCellEditingStyleInsert;        

    }else {

        return UITableViewCellEditingStyleDelete;

    }

//

UITableViewCell常用属性和方法:

重用机制:

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *simpleTableIdentifier=@"simpleIdentifier";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if(cell==nil)
    {
        cell=[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier];
    }
    NSUInteger row=[indexPath row];
    cell.text=[self.listData objectAtIndex:row];
    return  cell;
}

上述函数用来绘cell,第一个参数是代表用来绘cell的发起者,第二个参数是indexPath,通过该参数我们可以得到section和row,

表视图在iphone上一次只能显示有限的几行,但是表示图的数据量可以是很大的,如果我们为每一行数据量分配一个cell,那么开销将非常大。

同时我们发现,有些cell是当前显示,有些不是,当一个cell滚出屏幕时,另一些cell就会从另一边滚到屏幕上,如果滚到屏幕上的cell重新使用滚出屏幕的cell,那么系统就不会为创建或删除一个新的cell而浪费空间与时间。我们用simpleTalbeIdentifier来标示每个cell,调用[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier] ,看有这个标示的cell是否以前在可重用队列中出现过,如果有那直接使用即可,如果没有则为nil,cell=[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:创建新的cell。


第一、辅助图标的设置(默认为none)

typedefNS_ENUM(NSInteger, UITableViewCellAccessoryType) {

    UITableViewCellAccessoryNone,                  // don't show any accessory view

    UITableViewCellAccessoryDisclosureIndicator,   // regular chevron. doesn't track

    UITableViewCellAccessoryDetailDisclosureButton,// blue button w/ chevron. tracks

    UITableViewCellAccessoryCheckmark              // checkmark. doesn't track

};

设置方法:

cell.accessoryType=UITableViewCellAccessoryCheckmark;

第二、点击accessoryButton调用事件

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath

{

   NSLog(@"clickAccessoryButton");

}

第三、设置cell选中时的背景

typedefNS_ENUM(NSInteger, UITableViewCellSelectionStyle) {

    UITableViewCellSelectionStyleNone,

    UITableViewCellSelectionStyleBlue,

    UITableViewCellSelectionStyleGray

};

    cell.selectionStyle=UITableViewCellSelectionStyleGray;

第四、设置cell的背景

cell.backgroundView=**;

cell.selectedBackgroundView="**";

设置tableViewCell间的分割线的颜色

[theTableView setSeparatorColor:[UIColor xxxx ]];

第五、根据indexpath获取cell

UITableViewCell *cell=[tableViewcellForRowAtIndexPath:indexPath];

第六、根据index获取indexPath

    NSIndexPath *lastIndex=[NSIndexPathindexPathForRow:_indexinSection:0];

第七、放弃选择时的处理方法

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath*)indexPath

{

   NSLog(@"didDeselectRowAtIndexPath is %d",indexPath.row);

}




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好,关于 Swift 封装 UITableView 和 UICollectionView 的问题,我可以给你一些基本的介绍。 首先,UITableView 和 UICollectionView 都是 iOS 平台中常用的视图控件,用于展示列表和网格等数据。在 Swift 中,我们可以通过继承 UITableView 和 UICollectionView 类来自定义我们自己的表格和网格视图。 下面是一个简单的示例代码,展示如何封装 UITableView: ```swift import UIKit class MyTableView: UITableView, UITableViewDataSource, UITableViewDelegate { var data: [String] = [] override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) self.dataSource = self self.delegate = self // 注册单元格 self.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // UITableViewDataSource 协议方法 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = self.data[indexPath.row] return cell } // UITableViewDelegate 协议方法 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("选中了第 \(indexPath.row) 行") } } ``` 在这个示例代码中,我们自定义了一个名为 `MyTableView` 的类,继承自 `UITableView`。我们在 `init` 方法中设置了数据源和代理,并注册了一个单元格类型。在 `UITableViewDataSource` 和 `UITableViewDelegate` 协议方法中,我们实现了表格的行数、单元格内容和选中事件的处理。 类似地,我们也可以使用类似的方式封装 UICollectionView。需要注意的是,UICollectionViewDelegate 和 UICollectionViewDataSource 两个协议方法UITableView 中的函数名和实现方式略有不同,需要根据实际情况来进行调整。 希望这个简单的示例代码可以对你有所帮助。如果你有其他关于 Swift 的问题,欢迎随时提出!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值