在堆栈视图中按百分比约束对象

constraint object by percentage in a stackview

我想创建一个约束,它是 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
        
        
        
    }
    
    
}

您可以通过如下设置“widthAnchor”和“centerXAnchor”来实现。我们需要始终保持子视图和父视图的水平中心相同。而 child 的宽度应该是 super view 的 80%(这里 0.8 表示 80%)。

stackView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.8, constant: 0).isActive = true
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

将 stackView 的 widthAnchor 设置为 superView 的宽度(在本例中为视图控制器的视图)并将乘数值设置为 0.80

stackView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.80).isActive = true