【发布时间】:2020-06-26 14:18:15
【问题描述】:
我想创建一个 uiview 控制器宽度的 80% 的约束,而不是现在的 100%。我尝试使用 var percent 但它不起作用。代码应以 y 轴为中心。因此,左侧和骑行侧的 10% 不受约束。我正在尝试在堆栈视图中执行此操作。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Image View
let percent = ((UIScreen.main.bounds.midY) + (UIScreen.main.bounds.maxX * 0.8))
//Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width * percent).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text = "Hi World"
textLabel.textAlignment = .center
//Stack View
let stackView = UIStackView()
stackView.axis = NSLayoutConstraint.Axis.vertical
stackView.distribution = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing = 16.0
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)
//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
}
}
【问题讨论】:
标签: swift width frame subview stackview