UIView *tableHeader = [[UIView alloc] init];
tableHeader.backgroundColor = [UIColor cyanColor];
tableHeader.translatesAutoresizingMaskIntoConstraints = false;
tableView.tableHeaderView = tableHeader;//重要的代码1
UIImageView *bgIV = [[UIImageView alloc] init];
bgIV.contentMode = UIViewContentModeScaleAspectFit;
bgIV.image = [UIImage imageNamed:@"专辑详情背景"];
[tableHeader addSubview:bgIV];
bgIV.translatesAutoresizingMaskIntoConstraints = false;
[tableHeader addConstraint:[NSLayoutConstraint constraintWithItem:tableHeader attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:bgIV attribute:NSLayoutAttributeLeft multiplier:1 constant:0.]];
[tableHeader addConstraint:[NSLayoutConstraint constraintWithItem:tableHeader attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:bgIV attribute:NSLayoutAttributeRight multiplier:1 constant:0.]];
[tableHeader addConstraint:[NSLayoutConstraint constraintWithItem:tableHeader attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:bgIV attribute:NSLayoutAttributeTop multiplier:1 constant:0.]];
[tableHeader addConstraint:[NSLayoutConstraint constraintWithItem:tableHeader attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:bgIV attribute:NSLayoutAttributeBottom multiplier:1 constant:0.]];
UIImageView *logoIV = [[UIImageView alloc] init];
logoIV.contentMode = UIViewContentModeScaleAspectFit;
[logoIV sd_setImageWithURL:[NSURL URLWithString:self.track.coverUrlSmall] placeholderImage:[UIImage imageNamed:@"logoL"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
}];
[tableHeader addSubview:logoIV];
logoIV.translatesAutoresizingMaskIntoConstraints = false;
[tableHeader addConstraint:[NSLayoutConstraint constraintWithItem:tableHeader attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:logoIV attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
[tableHeader addConstraint:[NSLayoutConstraint constraintWithItem:tableHeader attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:logoIV attribute:NSLayoutAttributeLeft multiplier:1 constant:15.]];
[tableView.tableHeaderView layoutIfNeeded]; tableView.tableHeaderView = tableHeader; //重要的代码2
参考:TableHeaderView 使用AutoLayout自适应高度
网友评论