Center Align text in UITableViewCell problem

后端 未结 9 1258
梦如初夏
梦如初夏 2020-12-05 04:02

I\'m kinda new to Objective-C and iPhone development and I\'ve come across a problem when trying to center the text in a table cell. I\'ve searched google but the solutions

相关标签:
9条回答
  • 2020-12-05 04:36

    In same situation I created custom UITableViewCell with a custom label:

    MCCenterTextCell.h file:

    #import <UIKit/UIKit.h>
    
    @interface MCCenterTextCell : UITableViewCell
    
    @property (nonatomic, strong) UILabel *mainLabel;
    
    @end
    

    MCCenterTextCell.m file:

     #import "MCCenterTextCell.h"
    
    
    @interface MCCenterTextCell()
    
    
    @end
    
    
    @implementation MCCenterTextCell
    
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
    {
        self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
        if (self) {
    
            self.accessoryType = UITableViewCellAccessoryNone;
            self.selectionStyle = UITableViewCellSelectionStyleGray;
            _mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 320, 30)];
            _mainLabel.font = BOLD_FONT(13);
            _mainLabel.textAlignment = NSTextAlignmentCenter;
            [self.contentView addSubview:_mainLabel];
    
        }
        return self;
    }
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
    {
        [super setSelected:selected animated:animated];
    
        // Configure the view for the selected state
    }
    
    
    @end
    
    0 讨论(0)
  • 2020-12-05 04:40

    It doesn't work because the textLabel is only as wide as it needs to be for any given text. (UITableViewCell moves the labels around as it sees fit when set to the UITableViewCellStyleSubtitle style)

    You can override layoutSubviews to make sure the labels always fill the cell's entire width.

    - (void) layoutSubviews
    {
        [super layoutSubviews];
        self.textLabel.frame = CGRectMake(0, self.textLabel.frame.origin.y, self.frame.size.width, self.textLabel.frame.size.height);
        self.detailTextLabel.frame = CGRectMake(0, self.detailTextLabel.frame.origin.y, self.frame.size.width, self.detailTextLabel.frame.size.height);
    }
    

    Be sure to keep the height/y-position the same, because as long as the detailTextLabel's text is empty textLabel will be vertically centered.

    0 讨论(0)
  • 2020-12-05 04:41

    In case one wish to align the text to the right, I've had success adapting the solution described here.

    cell.transform = CGAffineTransformMakeScale(-1.0, 1.0);
    cell.textLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);
    cell.detailTextLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);
    
    0 讨论(0)
提交回复
热议问题