How do I create custom cells for a UITableView

2019-08-09 09:37发布

I am trying to create a UITableViewCell with multiple labels. I have been trying to do something similar (have "Name" and "Phone Number" left aligned and on two lines, then have "Age" right aligned in the cell and possibly vertically centered. I have tried the different UITableViewCellStyle styles but wanted to customize it so that the cell can contain 3 labels instead of just two. Any help would be greatly appreciated. Thanks in advance!

标签: ios4
3条回答
对你真心纯属浪费
2楼-- · 2019-08-09 09:53

One thing you can do is make a custom UITableViewCell in interface builder and add whatever labels etc you want to it and use that cell when you are populating your rows instead.

in your .h file you would need an IBOutlet UITableViewCell yourCellName

in your .m file

you can configure your custom cell in a method like the following:

-(void)setUpViewComponents{

        yourCellName.textLabel.text = @"some kind of text";

        yourCellName.textLabel2.text = @"some other text";


        //and so on

}

then in this method you can populate your table with the custom cell(s)

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



        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil) {

                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

        }

        cell = yourCellName; //you can make additional 
                             //changes to the cell here if you want


    return cell;
    }

Sorry for the rough example, hope it at least helps you get started.

查看更多
三岁会撩人
3楼-- · 2019-08-09 10:05

If you want to have your own cells in a UITableView you need to use a subclass of UITableViewCell. There are many examples of this, such as this one from Cocoa With Love.

查看更多
何必那么认真
4楼-- · 2019-08-09 10:13

Create a new class which extends UITableViewCell. I give you an example:

@interface YourCustomCell : UITableViewCell {
    UILabel *lb1,*lb2,*lb3;
}


@implement YourCustomCell

-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier{
    if (self=[super initWithFrame:frame reuseIdentifier:reuseIdentifier]){
          lb1=[UILabel alloc] initWithFrame:...];
          [self.contentView addSubview:lb1];
          ...
    }
    return self;
}
查看更多
登录 后发表回答