【发布时间】:2015-05-01 16:50:15
【问题描述】:
我有一个带有 tableView 的 ViewController。我已经在情节提要中设置了它。有没有办法以编程方式设置 tableView 的约束?我试图在 ViewController 中从我的 tableView 设置一个 IBOutlet 并为其添加约束。但这没有用。
这是我的视图控制器
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
addTableViewConstraints()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addTableViewConstraints() {
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
var topConstraint = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20)
var leadingContraint = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0)
var trailingConstraint = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0)
var bottomConstraint = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)
self.view.addConstraints([topConstraint, leadingContraint, trailingConstraint, bottomConstraint])
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = "Cell"
return cell
}
}
或者我是否也必须通过代码制作我的 tableView?
谢谢!
【问题讨论】:
-
你为什么要在代码中而不是在情节提要中这样做?只是好奇。
-
您的代码没有有什么作用?
-
@keithbhunter 我必须在单击按钮时更改约束。如果我在情节提要中做约束,我不知道该怎么做。
-
@DreamingInBinary 它在控制台中抛出一条错误消息:无法同时满足约束。
-
按下按钮时约束会如何变化?
标签: ios uitableview swift ios8 nslayoutconstraint