简体   繁体   中英

Can't center views in tableHeaderView with auto layout and storyboards

I can't center a view that has been placed as a subview of a UITableView's tableHeaderView in a storyboard using auto layout.

In a storyboard, I have a UITableView . I dragged a UIView (the red view) to the top, released, and it created a table header view automatically. I then dragged and dropped another UIView (the yellow view) on top of the table header view, resized, and applied some constraints to ensure it stays centered:

在此处输入图片说明

When I run the app on the simulator, here's what I get:

在此处输入图片说明

The yellow view is obviously not centered. However, the "Filter" button at the bottom is.

I know it's tricky to get the height right using auto layout and storyboards and table header views (and you can see that the height of the red view is definitely incorrect), but at this point, I'm just trying to solve for horizontally centering my yellow view.

Am I able to set this all up in my storyboard without having to configure my constraints in code?

确保您的UITableView在其父视图中设置了前导,尾随,底部,顶部约束。

Check the table header view and all sub views have Autoresize Subviews enabled:

Xcode屏幕截图显示“自动调整大小子视图”复选框

You can also force the table to re-render the header view by re-setting it to the same view:

[self.tableView setTableHeaderView:self.outletToHeaderView];

Update : to resize the table header view, give give it an appropriate frame in viewWillAppear :

CGRect newFrame = self.outletToHeaderView.frame;
newFrame.size.width = self.tableView.bounds.size.width;
newFrame.size.height = 44;
[self.outletToHeaderView setFrame:newFrame];
// Then reset it to force the table view to re-render/accommodate
[self.tableView setTableHeaderView:self.outletToHeaderView]

You need to use prototype cell from table view, than dequeue it with reusable identifier and return it contentView. Only that's do the trick

var headerView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.headerView = (self.tableView.dequeueReusableCellWithIdentifier("CustomHeaderCell") as! UITableViewCell).contentView
}

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return self.headerView
}

upd: Oh sorry, my example is written in Swift. But it's easy to understand how to do the same in Obj-C

In your file TableViewHeader:

override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        yourView.translatesAutoresizingMaskIntoConstraints = false
        yourView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    }

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