简体   繁体   中英

iOS UITableView AutoLayout Constraint Errors, Strange Behaviour

I'm seeing some strange behaviour in iOS 7.1. The same does not occur in iOS 8.

When loading a UITableViewController I'm getting a bunch of constraint errors that just don't make any sense (Unable to simultaneously satisfy constraints). I'm familiar with constraint language and how to debug these errors but for the life of me I cannot work out what's going on.

My table has a bunch of custom cells. For debug purposes I've reduced the cells to just one to isolate the constraint error. When rendered the table looks like this with the single custom cell displayed:

表格单元格已呈现

The constraint error is:

"<NSLayoutConstraint:0x7a098570 H:[UIImageView:0x7a0984c0(60)]>",
"<NSLayoutConstraint:0x7a098aa0 H:|-(8)-[UIImageView:0x7a0984c0]   (Names: '|':UITableViewCellContentView:0x7a097ed0 )>",
"<NSLayoutConstraint:0x7a098b30 H:[UILabel:0x7a097f70]-(12)-|   (Names: '|':UITableViewCellContentView:0x7a097ed0 )>",
"<NSLayoutConstraint:0x7a098b60 H:[UIImageView:0x7a0984c0]-(8)-[UILabel:0x7a097f70]>",
"<NSAutoresizingMaskLayoutConstraint:0x79ec3c60 h=--& v=--& H:[UITableViewCellContentView:0x7a097ed0(0)]>"

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7a098570 H:[UIImageView:0x7a0984c0(60)]>

The bit from that which is most confusing is the line:

H:[UITableViewCellContentView:0x7a097ed0(0)]

It appears the contentview of the cell has a zero width?!?

Because of this autolayout breaks the image width constraint (width 60). The errors keep coming breaking every constraint that goes against a zero-width contentview. Once the errors have finished outputting the cell is displayed correctly.

The cell is made up of an imageview and three uilabels:

单元设计

I cannot understand why the contentview would have a zero width or why these constraint errors would occur. Running in the simulator or device on iOS 7.1 gives the errors, running on simulator or device on iOS 8 does not!

Does anyone have a clue why this would be happening?

I found the answer.

I had started the project in iOS7 and then half way through I upgraded xcode when iOS 8 came out. The table views created after the upgrade were the ones exhibiting this behaviour.

I found that in the cellForRowAtIndexPath method of the table view controller if I placed this code after dequeuing the cell:

cell.contentView.frame = cell.bounds;
cell.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

It fixed the issue.

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