2017-01-29 22 views
0

我正在用cs193p快速学习,我遇到了UITextView.sizeThatFits(...)问题。它应该为popover视图返回一个推荐的大小以显示一个[int]数组作为文本。正如你在Paul Hegarty的例子中看到的(https://youtu.be/gjl2gc70YHM?t=1h43m17s),他得到了完美适合的没有滚动条的弹出式窗口。我使用几乎这是在此讲学相同的代码,而是我这有:为什么sizeThatFits()返回的尺寸太小?

enter image description here

text字符串等于[100],但sizeThatFits()方法返回一个尺寸过小即使有足够的可用空间,也可以很好地显示它。 它越来越好一点,我添加了一些文本之后,但仍不够精确,并与滚动条:

enter image description here

这里就是大小被设置代码的一部分:

override var preferredContentSize: CGSize { 
    get { 
     if textView != nil && presentingViewController != nil { 
     // I've added these outputs so I can see the exact numbers to try to understand how this works 
      print("presentingViewController!.view.bounds.size = \(presentingViewController!.view.bounds.size)") 
      print("sizeThatFits = \(textView.sizeThatFits(presentingViewController!.view.bounds.size))") 
      return textView.sizeThatFits(presentingViewController!.view.bounds.size) 
     } else { return super.preferredContentSize } 
    } 
    set { super.preferredContentSize = newValue } 
} 

我应该怎么做才能像讲座一样工作?

回答

1

看起来标签和其父视图之间有16 pt的边距。在返回popover的首选大小时,您需要考虑这一点。

你应该尝试以下操作:

  • 添加32这是一个从preferredContentSize

  • 返回在Interface Builder宽度,清除您的UILabel布局限制,然后重新添加顶部,底部,前导和尾部约束,并确保“约束到边距”选项未启用。

最后,而不是覆盖preferredContentSize,你可以简单地设置preferredContentSize当你的看法是准备好显示,你可以要求自动布局来选择最佳尺寸:

override func viewDidLayoutSubviews() { 
    self.preferredContentSize = self.view.systemLayoutSizeFitting(UILayoutFittingCompressedSize) 
} 

如果您的布局配置正确,systemLayoutSizeFitting(UILayoutFittingCompressedSize)将返回视图的最小可能尺寸,同时考虑所有边距和子视图。

+0

感谢您的咨询。我的'UITextView'已经被限制在页边距: 'Text View.top =顶部布局Guide.bottom; Text View.leading = leadingMargin; Text View.trailing = trailingMargin; Bottom Layout Guide.top = Text View.bottom;' 我已将它更改为 'Text View.leading = leadingMargin - 20; Text View.trailing = trailingMargin + 20;' (顶部和底部保持不变),现在它工作正常。 所以确切的问题是,我认为我应该将我的'UITextView'约束为由Xcode(包含页边距)而不是屏幕边缘所建议的蓝线。 – smocer

相关问题