【发布时间】:2018-01-24 10:31:12
【问题描述】:
我以编程方式设计了一个弹出视图,它有一个标题、tableView 和 2 个按钮。按钮水平放置在一行中。我已经很努力了,但我无法将按钮设置成一行(即水平)。
tableView 也应该根据单元格的数量来设置它的约束。它不应该滚动。非常感谢任何帮助或建议。 这是我的代码:
class PopUpMenu : UIView{
// The title label
lazy var titleLabel: UILabel = {
let label = UILabel(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
return label
}()
// The table view
lazy var tableView: UITableView = {
let tv = UITableView(frame: .zero)
tv.translatesAutoresizingMaskIntoConstraints = false
return tv
}()
// add buttons
lazy var previousButton : UIButton = {
let y = self.tableView.frame.origin.y+self.tableView.frame.height
let frame = CGRect(x: 10, y: y, width: 150, height: 36)
let button = UIButton()
button.frame = frame
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Previous", for: .normal)
return button
}()
lazy var nextButton : UIButton = {
let x = previousButton.frame.origin.x + previousButton.frame.width + 10
let y = self.tableView.frame.origin.y+self.tableView.frame.height
let frame = CGRect(x: x, y: y, width: previousButton, height: 36)
let button = UIButton()
button.frame = frame
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Next", for: .normal)
return button
}()
override func didMoveToSuperview() {
super.didMoveToSuperview()
// Add views
addSubview(titleLabel)
addSubview(tableView)
addSubview(previousButton)
addSubview(nextButton)
var constraints = [NSLayoutConstraint]()
let views: [String: UIView] = ["titleLabel": titleLabel, "tableView": tableView, "previousButton" : previousButton, "nextButton" : nextButton]
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[titleLabel]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[tableView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[previousButton]-[nextButton]-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[titleLabel(50)][tableView][previousButton][nextButton]|", options: [], metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
}
}
这是我的输出:
【问题讨论】:
-
使用堆栈视图可能更容易
-
let x = previousButton + previousButton + 10 ,在 nextButton 中检查这一行,我认为问题存在
-
@JaydeepPatel 抱歉,我打错了。立即查看
-
@Scriptable 我看到了例子但不明白怎么做?你能用代码解释一下吗?
-
我发现这个指南很有用:medium.com/the-traveled-ios-developers-guide/… 这里可能解释的太多了
标签: swift uiview uibutton constraints ios-autolayout