【问题标题】:constraint object by percentage in a stackview在堆栈视图中按百分比约束对象
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以通过设置 '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
      

      【讨论】:

      • 我将常数更改为乘数,它具有预期的效果。
      • 哦...对不起@FloydGertez,我想我错过了“乘数”部分,而是更新了常数值。但很高兴您尝试了自己的方法并解决了您的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多