ios - 向 uitableviewcell 添加文本或绘图

标签 ios objective-c uitableview

我有添加文本标签、副标题和附件图标的代码,如下所示:

cell.textLabel.text = @"Title";
cell.detailTextLabel.text = @"Subtitle";
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

// And I see code in the docs for an image:
cell.imageView.image = ...

但我希望图像所在的位置(左侧)是文本或标签(如在 Instagram 中)或画圈(如 Apple 收藏夹调用屏幕)。这是怎么做到的?

最佳答案

尽管使用 UITableViewCellStyleDefault 您可以免费获得 UITableViewCell 上的 imageView 属性并且您可以使用它,只是在在这种情况下,您想要精确控制 imageView 和标签在单元格上的放置,您需要选择自定义 UITableViewCell。以下是实现此目标的步骤:

第 1 步:创建一个新的 UITableViewCell 子类 MyCustomCell

@interface MyCustomCell : UITableViewCell

第 2 步:MyCustomCell.m 中实现 initWithStyle:reuseIdentifier: 方法并将任何自定义 View 添加到单元格内容 View 。

- (id)initWithStyle:(UITableViewCellStyle)iStyle reuseIdentifier:(NSString *)iReuseIdentifier {
    if ((self = [super initWithStyle:iStyle reuseIdentifier:iReuseIdentifier])) {
         MyView *myCustomView = [[MyView alloc] init];
         myCustomView.frame = CGRectMake(6.0f, 6.0f, 30.0f, 30.0f);
         [self.contentView addSubview:myCustomView];
    }

    return self;
}

第 3 步:实现 layoutSubviews 方法以精细控制您的单元格内容 subview 。

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(6.0f, 6.0f, 30.0f, 30.0f);
    GFloat textLabelXPosition = self.imageView.frame.origin.x + self.imageView.frame.size.width + 10;
    self.textLabel.frame = CGRectMake(textLabelXPosition, 0.0, contentRect.size.width - textLabelXPosition, contentRect.size.height);
}

第 4 步:最后在 TableView Controller 的 cellForRowAtIndexPath: 方法中使用 MyCustomCell 实例。

关于ios - 向 uitableviewcell 添加文本或绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492780/

相关文章:

ios - 基于 UITableview 单元格选择和取消选择,快速添加和删除项目到数组中

ios - tableView如何:cellForRowAtIndexPath: protocol method updating cell content in Cocoa Touch?

ios - 加载表格时 tableView outlet nil

xml - RestKit 中的 elementToPropertyMapping

ios - 父子 UIViewControllers IOS

iphone - 你如何将 NSString 拆分成组件部分?

html - 判断url内容是否发生变化

iphone - 获取当前正在使用的 UIKeyBoardType?或者在 UIKeyboardType 发生变化时捕获

ios - [SLComposeViewController initWithExtension :requestedServiceType:]_block_invoke + 84 崩溃

ios - Swift 中多个 UIViewContoller 中的 NSNotification 处理