【发布时间】:2016-06-24 08:35:30
【问题描述】:
所需视图:
在 Storyboard 中,我在 Autolayout 中创建了两个带有蓝色背景的标签。他们的立场永远不会改变。接下来,我想在蓝色背景标签下方cellForRowAtIndexPath 的代码中添加 1 到 10 个标签。
我正在努力将代码中添加的标签(棕色背景)与自动布局中创建的标签(蓝色背景)对齐。
以下是我失败的尝试:
两种失败的方法:
在
cellForRowAtIndexPath中获取“B AutoLayout 静态标签”的框架,并将X 位置用于动态标签。没用。添加约束也不起作用——也许我没有正确添加约束。
代码如下:
class TableViewController: UITableViewController {
var cellHeight = [Int: CGFloat]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 85.0
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
let xLocation = cell.labelBStatic.frame.origin.x
var yLocation = cell.labelBStatic.frame.origin.y
let height = cell.labelBStatic.frame.size.height
var startYLocation = yLocation + height + 20
var i = 0
if indexPath.row % 2 == 0 {
i = 5
} else {
i = 7
}
while i < 10 {
let aLabel = UILabel()
aLabel.backgroundColor = UIColor.orangeColor()
aLabel.text = "Label # \(i)"
cell.contentView.addSubview(aLabel)
addConstraints(aLabel, verticalSpacing: startYLocation)
startYLocation += 20
i++
}
print(startYLocation)
cellHeight[indexPath.row] = startYLocation
return cell
}
func addConstraints(labelView: UILabel, verticalSpacing: CGFloat) {
// set Autoresizing Mask to false
labelView.translatesAutoresizingMaskIntoConstraints = false
//make dictionary for views
let viewsDictionary = ["view1": labelView]
//sizing constraints
let view1_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view1(>=50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
labelView.addConstraints(view1_constraint_H)
//position constraints
let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[view1]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(verticalSpacing)-[view1]", options: NSLayoutFormatOptions.AlignAllLeading, metrics: nil, views: viewsDictionary)
view.addConstraints(view_constraint_H as! [NSLayoutConstraint])
view.addConstraints(view_constraint_V as! [NSLayoutConstraint])
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let height = cellHeight[indexPath.row] {
return height
}
return 0
}
下面是Storyboard 设置(两个标签都水平居中):
问题:如何让我在 cellForRowAtIndexPath 中创建的动态标签与在 Storyboard 中创建的静态标签左对齐,以匹配我想要的顶部视图?
【问题讨论】:
标签: ios uitableview autolayout swift2 ios9