0

I am having a problem with AutoLayout and layoutSubviews

I am using iOS9 SDK Beta

One of my dynamic content label has colored background so I need to add custom width for spacing.

Screenshot 1 (Looks Ok On View First Load) Looks ok on first load Screenshot 2 (Problem occurs when you start scrolling. Custom width is not working sometimes.) Problem occurs when you scroll This is the code block I used in my custom UITableViewCell

- (void)layoutSubviews;
{
    [super layoutSubviews];
    [lblTransactionType sizeToFit];
    CGRect rect = lblTransactionType.frame;
    [lblTransactionType setFrame:CGRectMake(rect.origin.x-5, rect.origin.y, rect.size.width+10, 18)];
}

I guess I should use dynamic constraints, but how?

Any kind of help highly appreciated.

Thanks.

ayalcin
  • 877
  • 1
  • 8
  • 16

1 Answers1

0

Try to subclass your UILabel and add lines like:

- (void)drawTextInRect:(CGRect)rect {
    UIEdgeInsets insets = {0, 5, 0, 5};
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

It will add padding to your UILabel, so no need to change frame in layoutSubviews method.

AlexZd
  • 2,152
  • 2
  • 18
  • 29
  • Hello AlexZd, Thank you for your comment. But this time Label's width is not wide enough. So text is spliting with (...) dots. I also tried to change the rect in UILabel's subclass but this time paddings disappeard again. UIEdgeInsets insets = {0, 5, 0, 5}; CGRect newRect = CGRectMake(rect.origin.x-10, rect.origin.y, rect.size.width+20, rect.size.height); [super drawTextInRect:UIEdgeInsetsInsetRect(newRect, insets)]; – ayalcin Sep 03 '15 at 13:59
  • [super layoutSubviews]; makes my label shorter. I need to find a solution for that. – ayalcin Sep 03 '15 at 14:16
  • @Hüseyin Avni YALÇIN Try to set this width inside cellForRowAtIndexPath method, no need to do it in layoutSubviews. Also you can set width constraint and set it's constant like: var cnst = constraints().filter({$0.firstAttribute == NSLayoutAttribute.Width}).first as! NSLayoutConstraint cnst.constant = width, sorry for Swift. – AlexZd Sep 05 '15 at 05:53