我有添加文本标签、副标题和附件图标的代码,如下所示:
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/