0

Below is a uicollectionviewcell, bar width must be according to number at right of it (vote count), event I log its width contants in console you can see it's calculated correctly, but on ui, two of them seems doesn't work well, if I scroll collectionview for several times it will be fixed, and then it will be fail again, how to set a view's contraint contant in a cell correctly?

enter image description here

code is too long but I want to summarize here
1) in viewcontroller's cellForItem
cell.setup()
cell.layoutIfNeeded()
return cell

2) in cell's setup()
setupBarWidths()

3) in setupBardWidhts()
resetAllWitdhs -> 0
calculate and set widths

is this correct way?

7
  • Show your code please? Commented May 12, 2016 at 8:05
  • Looks like a cell reuse issue. try to implement prepareForReuse in your cell, and set the constraint to 0. Commented May 12, 2016 at 8:51
  • added my code summary check please Commented May 12, 2016 at 17:09
  • @turushan, Did you create autolayout constraint for width? or did you just change the frame and call layoutIfNeeded ? Commented May 12, 2016 at 19:30
  • @Doro working with storyboard created width contraint, end setting it in code according to calculations Commented May 12, 2016 at 20:33

1 Answer 1

0

It depends upon how you are setting your constants for your subview inside uicollectionviewcell.

If your cell does not update properly constraints, possible solution is there

You must provide separate width constraint for your horizontal bar, and set it every time your reload cell.

"if I scroll collectionview for several times it will be fixed"

This problem occurs when you does not handle properly constraints changing, for example,you have "if - else " clause in your code, and you don't implement one branch.

Anyway, it's much easier to provide solution if you share your collectionView(_:cellForItemAt:)

UPDATED:

UICollectionView has many bugs internal, so one possible solution is to override UICollectionViewCell and insert the following method:

override var bounds: CGRect { didSet { contentView.frame = bounds } } 

See this thread for more info.

Sign up to request clarification or add additional context in comments.

1 Comment

added my code summary check please, I'm handling if else cases, mostly, cell is not good at first initialize, then it fixes itself after out screen, in screen...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.