【问题标题】:How to center button in horizonatal stackview?如何在水平stackview中居中按钮?
【发布时间】:2018-09-26 20:43:17
【问题描述】:

我有一个带有两个按钮的水平堆栈视图。现在我想,如果一个按钮被隐藏,其他应该在中心。

喜欢,

[x   x]
[  x  ] 

【问题讨论】:

    标签: ios swift autolayout uistackview


    【解决方案1】:

    将 UIStackView 的分布属性设置为 Fill Equally 从情节提要或以编程方式:

    stackView.distribution = .fillEqually
    

    一旦一个按钮被隐藏,另一个就会居中。

    【讨论】:

      【解决方案2】:

      使用一些隐藏的 UIViews 怎么样?

      • 在你的类中声明stackView:

        var myFirstStack: UIStackView!
        var bool = true
        

      bool 是一个布尔值,用于模拟您想要隐藏或显示按钮时的情况。

      • 初始化viewDidLoad中的stackView:

        myStack = UIStackView(arrangedSubviews: createButtons("1", "2"))
        let v1 = UIView()
        v1.isHidden = true
        let v2 = UIView()
        v2.isHidden = true
        myStack.insertArrangedSubview(v1, at: 1)
        myStack.addArrangedSubview(v2)
        myStack.translatesAutoresizingMaskIntoConstraints = false
        myStack.axis = .horizontal
        myStack.spacing = 20
        myStack.distribution = .fillEqually
        
        view.addSubview(myStack)
        

      它使用这个功能:

      func createButtons(_ named: String...) -> [UIButton] {
          var i = true
          return named.map { name in
              let btn = UIButton()
              btn.translatesAutoresizingMaskIntoConstraints = false
              btn.setTitle(name, for: .normal)
              btn.backgroundColor = i ? .yellow : .red
              i.toggle()
              btn.setTitleColor(.black, for: .normal)
              return btn
          }
      }
      
      • 添加自动布局约束:

        myFirstStack.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
        myFirstStack.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
        myFirstStack.heightAnchor.constraint(equalToConstant: 100).isActive = true
        myFirstStack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        

      这是目前的样子:

      • 当第三个按钮被点击时,UIViews 被隐藏或显示:

        @IBAction func hide(_ sender: Any) {
            myFirstStack.arrangedSubviews[0].isHidden = bool  //This is the button to hide
            myFirstStack.spacing = bool ? -100 : 20           //Adjust the spacing to your liking 
            myFirstStack.arrangedSubviews[1].isHidden = !bool //Hide or show the first UIView
            myFirstStack.arrangedSubviews[3].isHidden = !bool //Hide or show the second UIView
            bool.toggle()
        }
        

      结果如下:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-20
        • 2013-03-02
        • 1970-01-01
        • 2016-11-02
        • 2016-07-18
        • 2020-03-14
        • 2017-07-29
        相关资源
        最近更新 更多