【问题标题】:Creating a custom UITableViewCell创建自定义 UITableViewCell
【发布时间】:2013-02-28 04:15:34
【问题描述】:

我正在尝试创建自定义 UITableViewCell。

在 XCode 4.6 界面生成器中,我已将单元格的 Style 属性设置为自定义。并使用拖放向单元格添加控件。 2 个 UILables 和一个 UIButton。看起来像这样。

我创建了一个派生自 UITableViewCell 的单独类来分配 3 个 UI 元素的属性并在那里进行更改。我还从 Identity Inspector 将单元格的自定义类设置为 DashboardCell。

DashboardCell.h

#import <UIKit/UIKit.h>

@interface DashboardCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *numberOfMails;
@property (weak, nonatomic) IBOutlet UILabel *mailType;
@property (weak, nonatomic) IBOutlet UIButton *numberOfOverdueMails;

@end

DashboardCell.m

#import "DashboardCell.h"

@implementation DashboardCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.numberOfOverdueMails setBackgroundColor:[UIColor colorWithRed:244/255.0f green:119/255.0f blue:125/255.0f alpha:1.0f]];
        [self.numberOfOverdueMails setTitle:@"lol" forState:UIControlStateNormal];
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

在 TableViewController 中,我修改了以下方法以返回我的自定义单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    DashboardCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[DashboardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    return cell;
}

我的问题是即使显示了自定义按钮,我所做的更改(更改按钮的背景颜色,更改一个 UILabel 的标题)也没有显示。这里似乎有什么错误?

【问题讨论】:

    标签: objective-c uitableview ios6 storyboard custom-controls


    【解决方案1】:

    不会调用方法initWithStyle:reuseIdentifier:,因为您正在使用界面生成器来创建单元格。

    您可以通过覆盖方法awakeFromNib.来设置背景颜色和标题

    你也可以在tableView:cellForRowAtIndexPath:方法中设置这些

    【讨论】:

      【解决方案2】:

      如果您从 xib 或情节提要中获取单元格,dequeueReusableCellWithIdentifier:forIndexPath: 将始终返回一个单元格——如果存在,它将重用它,如果不存在,它将从 IB 中的模板创建一个。因此,您的 if(cell ==nil) 子句永远不会得到满足,实际上不再需要。如果要使用init 方法,请使用initWithCoder:

      【讨论】:

        猜你喜欢
        • 2013-08-29
        • 2011-12-29
        • 1970-01-01
        • 2011-12-13
        • 2014-04-12
        • 1970-01-01
        • 2015-03-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多