简体   繁体   中英

UITableViewCell UILabel Multiple Lines Aligment

I'm using a standard prototype cell with a label and a detail text. I set the detail text to be two lines and set the text to something with a line break. This works fine - however, the (left aligned) main label has lost its vertical centering, though I didn't change any of its attributes.

This is what it looks like in Storyboard:

Interface Builder的屏幕截图

"Title" should be vertically centered.

You can subclass the UITableViewCell and do your layout in the initWithStyle method. For ex:

MyCustomCell.h file:

@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 file:

#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;
}

In the class file where you have cellForRowAtIndexPath method, make sure include the #import "MyCustomCell.h" and use MyCustomCell instead of UITableViewCell to allocate the cell. And assigning data to labels as so:

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

You can use a custom cell in which you can define the attributes of the custom properties.The size of the text label is not fixed. I think this is the reason why the alignment does not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM