[英]Changing custom view's frame on orientation change in subclass using Swift
[英]Dynamically Changing Frame of View Swift
我有一個UICollectionView
。 UICollectionViewCell
包含一個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
}
如果您使用的是自動版式,則只需刪除文本組件上的寬度和高度限制,它就會相應地適應文本大小。
接下來應該做的是計算字符串的textSize
- (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;
}
注意:如果未選中SizeClasses,則將顯示黃色警告,因為您沒有設置寬度和高度,而忽略它們。
更新:您可以在此處找到有關此主題的優秀教程。
作為討論在這里 ,
將尾隨的和領先的NSLayoutConstraints添加到messageTextView
解決此問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.