简体   繁体   English

UITableView的HeaderFooterView不根据大小类的宽度拉伸

[英]HeaderFooterView of UITableView not stretching according to size class width

I have a tableview with a custom header i make from a nib file. 我有一个带有从笔尖文件中制作的自定义标头的tableview。

The size class of the nib file is Any x Any, but the width of the Header does not stretch to fit on iPhone 6 & iPhone 6Plus. 笔尖文件的大小级别为Any x Any,但是Header的宽度无法拉伸以适合iPhone 6和iPhone 6Plus。

Here's how i make the HeaderFooterView 这是我制作HeaderFooterView

let headerCell = UINib(nibName: "TeamCheckHeaderTableViewCell", bundle: nil)
tblTeamCheck.registerNib(headerCell, forHeaderFooterViewReuseIdentifier: TeamCheckHeaderTableViewCell.description())

In viewForHeaderInSection viewForHeaderInSection

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerCell = tblTeamCheck.dequeueReusableHeaderFooterViewWithIdentifier(TeamCheckHeaderTableViewCell.description()) as! TeamCheckHeaderTableViewCell

    return headerCell
}

Here's how it looks on a iPhone 5 这是在iPhone 5上的外观

在此处输入图片说明

Here's how it looks on a iPhone 6 这是在iPhone 6上的外观

在此处输入图片说明

The same with 6Plus, It seems like the width of the HeaderFooterView is constant 320 . 与6Plus相同,似乎HeaderFooterView的宽度为常数320

尝试将headerCell.layoutIfNeeded()添加到func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

Found a solution, but probably not the best - Still open for better solutions . 找到了解决方案,但可能不是最好的- 仍在寻求更好的解决方案

I hardcoded the width of the header cell to be 414 in the .xib file - Which is the width of iPhone 6 Plus. 我在.xib文件中将标头单元格的宽度硬编码为414,这就是iPhone 6 Plus的宽度。

Then programmatically calculate the position of the center label, and set the constraint so it will be centered, no matter which iPhone screen it is. 然后以编程方式计算中心标签的位置,并设置约束以使其居中,无论它位于哪个iPhone屏幕上。

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerCell = tblTeamCheck.dequeueReusableHeaderFooterViewWithIdentifier(TeamCheckHeaderTableViewCell.description()) as! TeamCheckHeaderTableViewCell

    //Calculate the diff and set the new constraint
    let tableViewWidth = tableView.frame.size.width
    let headerCellWidth : CGFloat = headerCell.frame.size.width
    let diff =  headerCellWidth - tableViewWidth
    headerCell.centerConstraint.constant = diff/2

    return headerCell
}

I created the constrains as a variable in the TeamCheckHeaderTableViewCell 我在TeamCheckHeaderTableViewCell约束创建为变量

@IBOutlet weak var centerConstraint: NSLayoutConstraint!

Check the class type of the item inside your xib. 检查xib内部项目的类类型。 You might have used a UITableViewCell. 您可能已经使用过UITableViewCell。 Replace it with a UIView and it will start stretching. 用UIView替换它,它将开始拉伸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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