mankee mankee - 6 months ago 20
iOS Question

Dynamically Changing Frame of View Swift

enter image description here

I have a

UICollectionView
. The
UICollectionViewCell
contains a
UITextView
. I want to dynamically change the frame of the
UITextView
. I use the following code. The problem is that sometimes this works, other times it doesn't and no change is made to the frame. I am not sure what the issue is.

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
}

Answer

As discussed Here,

Adding trailing and leading NSLayoutConstraints to the messageTextView fixed the problem