ios - 滚动时 TableView UILabel 对齐方式发生变化

标签 ios objective-c uitableview uilabel

我有一个带有 3 个 UILabelTableView:标题、作者姓名和类别以及一个 UIImage。所有单元格都应类似于此布局:

Cell Layout

正确的单元格布局:

Proper Label Alignment

当应用程序由于某种原因启动时,某些单元格的标题 UILabel 对齐方式不正确:

Incorrect title label alignment

Incorrect title label alignment

滚动 TableView 几次后,这些单元格最终会正确对齐。我不太确定是什么原因造成的。

我创建了一个 Custom TableView Cell 类(遵循 tutorial )

CustomTableViewCell.h

@interface CustomTableViewCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UIImageView *image;
@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
@property (nonatomic, weak) IBOutlet UILabel *authorLabel;
@property (nonatomic, weak) IBOutlet UILabel *categoryLabel;
@end

CustomTableViewCell.m

@implementation CustomTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
   // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.contentView layoutIfNeeded];
    self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame);
    [self.titleLabel sizeToFit];
    [self.titleLabel setNumberOfLines:0];
}

@end

这是在 ViewController 中实现此类的方式:

@interface CurrentIssueViewController () {
    CurrentIssueModel *_currentIssueModel;
    Article *_selectedArticle;
}

@end

@implementation CurrentIssueViewController

static NSString *cellIdentifier = @"BasicCell";
UIActivityIndicatorView *activityView;
//@synthesize _feedItems;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangePreferredContentSize:)name:UIContentSizeCategoryDidChangeNotification object:nil];

    // Create array object and assign it to _feedItems variable
    self._feedItems = [[NSArray alloc] init];

    // Create new HomeModel object and assign it to _homeModel variable
    _currentIssueModel = [[CurrentIssueModel alloc] init];

    // Set this view controller object as the delegate for the home model object
    _currentIssueModel.delegate = self;

    // Call the download items method of the home model object
    [_currentIssueModel downloadItems];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIContentSizeCategoryDidChangeNotification object:nil];
}

- (void)didChangePreferredContentSize:(NSNotification *)notification
{
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)itemsDownloaded:(NSArray *)items
{
    // This delegate method will get called when the items are finished downloading

    // Set the downloaded items to the array
    self._feedItems = items;

    [activityView stopAnimating];

    // Reload the table view
    [self.tableView reloadData];
}

#pragma mark Table View Delegate Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of feed items (initially 0)
    return self._feedItems.count;
}

/* ================================================== */

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    [self configureCell:cell forRowAtIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell isKindOfClass:[CustomTableViewCell class]])
    {
        CustomTableViewCell *textCell = (CustomTableViewCell *)cell;

        Article *article_item = self._feedItems[indexPath.row];

        NSString *fulltitle = article_item.Title;

        if (article_item.Subtitle != nil && article_item.Subtitle.length != 0) {
            fulltitle = [fulltitle stringByAppendingString:@": "];
            fulltitle = [fulltitle stringByAppendingString:article_item.Subtitle];
        }
        textCell.titleLabel.text = fulltitle;

        if ([article_item.Author isEqualToString:@"accountant"]) {
            textCell.authorLabel.text = @"";
        }
        else {
            textCell.authorLabel.text = article_item.Author;
        }

        textCell.categoryLabel.text = article_item.Cat_Name;

        textCell.titleLabel.numberOfLines = 0;
        textCell.titleLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];

        textCell.authorLabel.font = [UIFont fontWithName:@"Arial" size:10.0f];
        textCell.categoryLabel.font = [UIFont fontWithName:@"Arial" size:10.0f];
        textCell.categoryLabel.textAlignment = NSTextAlignmentRight;

        NSURL *url;

        if ([article_item.ImageUrl length] != 0) {
            url = [NSURL URLWithString:article_item.ImageUrl];
        }
        else {
            url = [NSURL URLWithString:@"imageurl"];
        }

        [textCell.image sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"default_image.jpg"]];
    }
}

- (CustomTableViewCell *)prototypeCell
{
    if (!_prototypeCell)
    {
        _prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    return _prototypeCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];

    self.prototypeCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.prototypeCell.bounds));

    [self.prototypeCell layoutIfNeeded];

    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height+1;
}

/* ================================================== */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Set selected article to var
    _selectedArticle = self._feedItems[indexPath.row];
    [self performSegueWithIdentifier:@"detailSegue" sender:self];

}

#pragma mark Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get reference to the destination view controller
    ArticleViewController *articleVC = segue.destinationViewController;

    // Set the property to the selected article so when the view for
    // detail view controller loads, it can access that property to get the feeditem obj
    articleVC.selectedArticle = _selectedArticle;
}

@end

我想这与 forRowAtIndexPath 有关,但我无法真正弄清楚问题是什么。

更新:

我注意到标题 UILabel 还有另一个问题。每当您选择一个单元格,在另一个 ViewController 中查看文章并返回到 UITableView 时,标题标签位于 Center Left 而不是左上角。再次滚动后,标题标签会调整到正确的位置。

最佳答案

您已为 NIB/ Storyboard选择了自动布局,但尚未向您的单元格添加任何约束。向您的单元格添加布局约束。有一个很好的答案here这在一些细节上解释了它:

关于ios - 滚动时 TableView UILabel 对齐方式发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25505609/

相关文章:

ios - webview 中的 pdf 文件不滚动

iphone - UITableView 单元格索引路径

ios - UISearchController 过滤器 Swift

iOS 相比通过整个类来查看或逐个设置哪个设计更好

ios - 如何在视觉格式约束中告诉 tableviewcell 类标签名称?

ios - UITableViewCells 中的图像加载错误

ios - 使用prepareForReuse函数从UITableCell类内的ViewController重置var

ios - 恼人的 Xcode 自动补全 @string 和 @selector?

ios - UICollectionViewCell 根据通用应用程序中的文本量自动调整垂直大小

ios - 'NSRangeException',原因 : '*** -[NSBigMutableString characterAtIndex:]: Index 1258 out of bounds; string length 1176'