在UICollectionViewCell中更改标签位置

我们有一个UICollectionView ,它在Storyboard上有一个原型单元格。 单元格中有一个UILabel (“ label ”),没有自动布局。

我们在-collectionView:cellForItemAtIndexPath: cellForItemAtIndexPath中有条件地设置标签的框架-collectionView:cellForItemAtIndexPath:使用setFrame,如下所示:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { CategoryCell *cell; cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Category" forIndexPath:indexPath]; ... if (self.isViewTypeList) { [((CategoryCell *)cell).label setFrame:FRAME_RECT]; } ... return cell; } 

我们已经检查了它,似乎首先它调用标签的-setFrame:当它到达dequeing时使用Storyboard值,然后我们的代码跟随,这将正确设置新帧。 除了这些之外没有其他电话,但标签仍保留在屏幕上的原始位置。

怎么了? 为什么新框架设置不正确? 还有其他的东西在过度吗? 我是否必须以某种方式重新布局或刷新它?

请尝试以下步骤。 这对你有用 –

  • 在故事板或XIB文件中选择原型单元格
  • 选择要更改框架的标签
  • Attributes Inspector (View Section)设置它的tag属性,如set tag = 101

在你的代码部分之后执行此操作 –

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { //... CategoryCell *cell; cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Category" forIndexPath:indexPath]; //... if (self.isViewTypeList) { UILabel *lbl = (UILabel *)[cell viewWithTag:101]; [lbl setFrame:FRAME_RECT]; } //... } 

祝你好运!

从xib取消选中Autolayout。 它可能有助于改变框架。

尝试:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { //... //instead of //CategoryCell *cell; //cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Category" // forIndexPath:indexPath]; CategoryCell *cell = (CategoryCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Category" forIndexPath:indexPath]; //sure reuse-identifier is "Category"? //... if (self.isViewTypeList) { //instead of //[((CategoryCell *)cell).label setFrame:FRAME_RECT]; [cell.label setFrame:FRAME_RECT]; } //... return cell; } 

也请浏览此链接,看看您是否遗漏了一些关键步骤:
http://ashfurrow.com/blog/uicollectionview-example

Autolayout将覆盖您对setFrame:的调用setFrame: 。 您可以使用标签的约束在单元格中添加一些出口,并更改这些出口以更改框架。