【发布时间】:2017-02-10 03:04:32
【问题描述】:
我有一个UITableViewController,我以编程方式创建(没有 xib)。我正在尝试使用从具有自动布局约束的 xib 加载的UIView,并将其用作我的tableHeaderView(不是节标题)。然后我需要根据UILabel 的缩放自动调整UIView 的大小,其中将包含动态文本。
这就是我创建UIView 的方式:
class HeaderTableLargeHeaderView: UIView {
// Our title label with autolayout constraints
@IBOutlet weak var titleLabel: UILabel!
// Convience method to load for xib
class func instanceFromNib() -> UIView {
return UINib(nibName: "HeaderTableLargeHeaderView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.preferredMaxLayoutWidth = titleLabel.bounds.width
}
}
然后我尝试像这样在我的UITableViewController 中加载它:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let header = HeaderTableLargeHeaderView.instanceFromNib()
header.frame = CGRectMake(0, 0, self.view.frame.size.width, 100)
let height = header.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var frame = header.frame
frame.size.height = height
header.frame = frame
header.setNeedsLayout()
header.layoutIfNeeded()
tableView.tableHeaderView = header
}
但是我得到了这些错误:
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x7c061050 V:[UILabel:0x7c0b77e0'Label']-(8)-| (Names: '|':Care_Com.HeaderTableLargeHeaderView:0x7c04a550 )>",
"<NSLayoutConstraint:0x7c0c6590 V:|-(8)-[UILabel:0x7c0b77e0'Label'] (Names: '|':Care_Com.HeaderTableLargeHeaderView:0x7c04a550 )>",
"<NSLayoutConstraint:0x797576d0 'UIView-Encapsulated-Layout-Height' V:[Care_Com.HeaderTableLargeHeaderView:0x7c04a550(0)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7c061050 V:[UILabel:0x7c0b77e0'Label']-(8)-| (Names: '|':Care_Com.HeaderTableLargeHeaderView:0x7c04a550 )>
我想我理解但不知道如何解决。我认为它告诉我的是它无法正确设置UILabel 的约束,因为它不知道UIView 的边界......我认为。
如果我这样做,我不会收到任何错误并且加载正常,但是高度是静态的 100。
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let header = HeaderTableLargeHeaderView.instanceFromNib()
header.frame = CGRectMake(0, 0, self.view.frame.size.width, 100)
header.setNeedsLayout()
header.layoutIfNeeded()
tableView.tableHeaderView = header
}
我试过设置这些仍然没有帮助:(
self.view.translatesAutoresizingMaskIntoConstraints = false
self.tableView.translatesAutoresizingMaskIntoConstraints = false
我也试过这样做:
header.translatesAutoresizingMaskIntoConstraints = false
【问题讨论】:
-
我认为您的约束已经足够了,但是您已经编写了一些额外的代码。我可以用真实的例子来解决。将您的代码发布为带有单个控制器和这些文件的示例项目。我会解决的。
-
太棒了!!!我会尽快建立一个示例项目
-
@M.K.我在这里创建了示例项目:github.com/coryhymel/HeaderTest/tree/master 再次感谢您!!!
标签: ios swift uiview autolayout xib