【问题标题】:UITableViewCell UILabel Multiple Lines AligmentUITableViewCell UILabel 多行对齐
【发布时间】:2012-06-18 09:51:31
【问题描述】:

我正在使用带有标签和详细信息文本的标准原型单元格。我将详细文本设置为两行,并将文本设置为带有换行符的内容。这很好用 - 但是,(左对齐)主标签失去了垂直居中,尽管我没有更改它的任何属性。

这就是 Storyboard 中的样子:

“标题”应垂直居中。

【问题讨论】:

  • 我从来没有使用故事板,你能重做主标签的矩形以覆盖整个单元格,这样它就会自动垂直居中吗?

标签: ios xcode uitableview vertical-alignment


【解决方案1】:

您可以使用自定义单元格,您可以在其中定义自定义属性的属性。文本标签的大小不固定。我认为这就是对齐不起作用的原因。

【讨论】:

  • 这让我走上了正轨。将类型设置为自定义确实可以解决问题。我仍然必须创建一个 UITableViewCell 子类来将标签连接到代码,但可能没有办法解决这个问题。谢谢!
  • 如果不想使用自定义的UITableViewCell,可以重写方法-(void)layoutSubviews;对于UITableViewCell的分类。在这个方法中,你可以设置所有子视图的属性,如textLabel、imageView等。
【解决方案2】:

您可以继承 UITableViewCell 并在 initWithStyle 方法中进行布局。例如:

MyCustomCell.h 文件:

@interface MyCustomCell : UITableViewCell
{
    UILabel *_label1;
    UILabel *_label2;
    UILabel *_titleLabel;
}

@property (nonatomic, strong) UILabel *label1;
@property (nonatomic, strong) UILabel *label2;
@property (nonatomic, strong) UILabel *titleLabel;
@end

MyCustomCell.m 文件:

#import "MyCustomCell.h"

@implementation MyCustomCell
@synthesize label1 = _label1;
@synthesize label2 = _label2;
@synthesize titleLabel = _titleLabel;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.label1 = [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];  //x: x coordinate, y: y coordinate, w is width , h is height
        self.label2 = [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];
        self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];
        self.titleLabel.font = [UIFont fontWithName:@"Times New Roman" size:30.0f]; //change font name and size per your needed.
        [self addSubview:self.label1];
        [self addSubview:self.label1];
        [self addSubview:self.titleLabel];
    }
    return self;
}

在您拥有cellForRowAtIndexPath 方法的类文件中,确保包含#import "MyCustomCell.h" 并使用MyCustomCell 而不是UITableViewCell 来分配单元格。并将数据分配给标签:

cell.label1.text = xxxx;
cell.label2.text = xxxx;
cell.titleLabel.text = xxxx;

【讨论】:

  • 谢谢!我知道这是可能的,但我想保存那个额外的课程。
猜你喜欢
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 2018-08-31
  • 2023-03-17
  • 2016-08-22
  • 1970-01-01
相关资源
最近更新 更多