Search code examples
swiftwidthframesubviewstackview

constraint object by percentage in a stackview


I want to create a constraint that is 80 percent of the width of the uiview controller not a 100 percent which is what it is now. I tried using the var percent but its not working. The code should be centered on the y axis. So 10 percent on the left side and ride side are not covered by the constraint. I am trying to do this in a stack view.

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
        
        
        
    }
    
    
}

Solution

  • Set the widthAnchor of stackView with that of superView's width (in this case view controller's view) and set multiplier value as 0.80

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