1

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

2 Answers2

2

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

Ashish Chauhan
  • 396
  • 2
  • 7
0

You can achieve this by setting 'widthAnchor' and 'centerXAnchor' like below. We need to always keep horizontal center of child view and super view same. Whereas width of child should be 80 percentage(here 0.8 indicates 80%) of super view.

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
Om Prakash
  • 51
  • 4
  • 1
    I change constant to multiplier and it is having the desired effect. –  Jun 26 '20 at 14:43
  • Oh... sorry for that @FloydGertez , I think I missed that 'multiplier' part and instead updated constant value. But glad you tried that your own and it resolved your issue. – Om Prakash Jun 30 '20 at 15:08