2016-05-29 130 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的好教程。