【问题标题】:Dynamic UILabel which has custom width does not apply while scrolling in UITableView with AutoLayout具有自定义宽度的动态 UILabel 在使用 AutoLayout 在 UITableView 中滚动时不适用
【发布时间】:2015-09-03 09:28:43
【问题描述】:

我在使用 AutoLayout 和 layoutSubviews 时遇到问题

我正在使用 iOS9 SDK 测试版

我的一个动态内容标签有彩色背景,所以我需要为间距添加自定义宽度。

屏幕截图 1(第一次加载时看起来不错) 屏幕截图 2(开始滚动时出现问题。自定义宽度有时不起作用。) 这是我在自定义 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)];
}

我想我应该使用动态约束,但是如何?

非常感谢任何形式的帮助。

谢谢。

【问题讨论】:

标签: objective-c uitableview ios9 ios-autolayout layoutsubviews


【解决方案1】:

尝试继承你的 UILabel 并添加如下行:

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

它会为你的 UILabel 添加填充,因此无需在 layoutSubviews 方法中更改框架。

【讨论】:

  • 您好 AlexZd,感谢您的评论。但是这次Label的宽度不够宽。所以文本用(...)点分割。我还尝试更改 UILabel 子类中的矩形,但这次填充再次消失了。 UIEdgeInsets insets = {0, 5, 0, 5}; CGRect newRect = CGRectMake(rect.origin.x-10, rect.origin.y, rect.size.width+20, rect.size.height); [超级drawTextInRect:UIEdgeInsetsInsetRect(newRect, insets)];
  • [超级布局子视图];使我的标签更短。我需要为此找到解决方案。
  • @Hüseyin Avni YALÇIN 尝试在 cellForRowAtIndexPath 方法中设置此宽度,无需在 layoutSubviews 中设置。您也可以设置宽度约束并将其设置为常量: var cnst = constraints().filter({$0.firstAttribute == NSLayoutAttribute.Width}).first as! NSLayoutConstraint cnst.constant = width,对不起 Swift。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多