2016-05-29 218 views
1

enter image description here动态更改视图Swift

我有一个UICollectionViewUICollectionViewCell包含UITextView。我想动态更改UITextView的框架。我使用下面的代码。问题在于有时候这是有效的,其他时候不会,框架也不会改变。我不确定问题是什么。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("message_cell" , forIndexPath: indexPath) as! DisplayMessageCollectionViewCell 

    if let messageText = "testing" { 
     let size = CGSizeMake(250, 1000) 
     let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin) 
     let estimatedFrame = NSString(string: messageText).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil) 

     if let user_id = NSUserDefaults.standardUserDefaults().stringForKey("userId") { 
      if (user_id == "testing") { 

        cell.messageTextView.frame = CGRectMake(view.frame.width - estimatedFrame.width - 16 - 8, 0, estimatedFrame.width + 16, estimatedFrame.height + 20) 

      } 
      else { 

        cell.messageTextView.frame = CGRectMake(48 + 3, 0, estimatedFrame.width + 15, estimatedFrame.height + 20) 

      } 
     } 

    } 



    return cell 
} 
+0

目前,做的所有单元格的大小250×1000,即使他们的帧进行复位? – Lahav

+0

不,他们不.. – Alk

+0

所以重置框架没有问题? – Lahav

回答

1

正如所讨论Here

添加拖尾和先行NSLayoutConstraints到messageTextView固定的问题

1

如果您使用的是AutoLayout,只需删除文本组件的宽度和高度约束,它就会相应地适应文本大小。

你应该做的下一件事是

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
CGSize maximumLabelSize = CGSizeMake(yourCellWidth, FLT_MAX); 

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabelFont constrainedToSize:maximumLabelSize lineBreakMode: UILineBreakModeWordWrap]; 
    return expectedLabelSize; 
} 

注意计算字符串的TEXTSIZE:如果你没有SizeClasses检查,它会显示你的黄色警告,因为你没有宽度和高度设置,但只是忽略它们。

更新:你可以找到关于这个主题here的好教程。