简体   繁体   English

在UITableView页脚中动态设置和调整标签大小

[英]Dynamically setting and resizing label in UITableView Footer

In my app, I'm updating the footer text of my table view dynamically when I select a cell. 在我的应用中,当我选择一个单元格时,我将动态更新表格视图的页脚文本。 Unfortunately the way I'm doing so seems to alter the frame of the UILabel within my UIView . 不幸的是,我这样做的方式似乎改变了UIView UILabel的框架。 For example, when I tap a cell, the width of my label becomes something between 950 and 1200. When in reality the width should be (at most) the width of the view. 例如,当我点击一个单元格时,我的标签宽度变为950到1200之间的某个值。实际上,宽度应该(最多)是视图的宽度。 Here's my code: 这是我的代码:

def tableView(tableView, viewForFooterInSection:section)
  (section != (self.sections.count - 1)) ? footer_view : nil
end

def tableView(tableView, heightForFooterInSection: section)
  if section != (self.sections.count - 1)
    footer_label.frame.size.height + 20.0
  else
    1.0
  end
end

def tableView(tableView, didSelectRowAtIndexPath: indexPath)
  tableView.beginUpdates
  footer_label.text = "Details: #{updated_details}"
  footer_label.sizeToFit
  tableView.endUpdates
end


def footer_view
  @footer_view ||= UIView.alloc.initWithFrame(CGRectZero).tap do |fv|
    fv.addSubview(footer_label)
  end
end

def footer_label
  @footer_label ||= UILabel.alloc.initWithFrame(CGRectZero).tap do |pl|
    pl.frame = CGRect.new(
      [15, 10],
      [self.view.frame.size.width - 30, self.view.frame.size.height]
    )
    pl.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2)
    pl.numberOfLines = 0
    pl.lineBreakMode = NSLineBreakByWordWrapping
    pl.text          = ""
    pl.sizeToFit
  end
end

I'm guessing calling sizeToFit is part of the problem? 我猜是调用sizeToFit是问题的一部分吗?

I think you'll need to use a dynamic height for the footer. 我认为您需要为页脚使用动态高度。

tableView.heightForFooterInSection = UITableViewAutomaticDimension
tableView.estimatedSectionFooterHeight = 25.0

Remember that you have to set the constraints of the UILabel. 请记住,您必须设置UILabel的约束。 Maybe you'll have to update the section to change the height. 也许您必须更新该部分以更改高度。

I thought I had tried this but maybe my order was off. 我以为我已经尝试过了,但是也许我的订单被取消了。 Either way, I solved it by setting the footer's frame again inside of beginUpdates / endUpdates : 无论哪种方式,我都通过在beginUpdates / endUpdates内部再次设置页脚框架来解决:

tableView.beginUpdates
frame = footer_label.frame
footer_label.text = "Plan Details: #{updated_details}"
frame.size.width = self.view.frame.size.width - 30
footer_label.frame = frame
footer_label.sizeToFit
tableView.endUpdates

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM