如何调整两个并排的UI按钮的大小

时间:2017-10-05 09:53:33

标签: ios swift uibutton autolayout

我有两个并排的UI按钮。 我需要根据以下条件调整两个UI按钮的大小:

2个UI按钮的布局:

     (1)              (2)
 |-------------------||-|
 | UIButton          ||B|
 |-------------------||-|

1)在开始阶段,具有约束的UI按钮(1):右8点和左点:12点,以便我可以在UI按钮(1)的左侧放置另一个UI按钮2,如上所示

问题:

我在这种情况下使用计时器。当时间到了。
如何以编程方式使两个UI按钮具有相等的宽度和它们之间的小间隙,使得UIButton(1)宽度将减小并且UIButton(2)宽度将增加

这些UI按钮在开始阶段会有约束。

我可以使用isHidden用于Ui_button(2),但是有更好的方法不显示它吗?

非常感谢您的帮助。

由于

2 个答案:

答案 0 :(得分:0)

我认为您可以使用EqualWidths约束。

故事板中的约束

enter image description here

enter image description here

ViewController代码

class ViewController: UIViewController {
    @IBOutlet weak var button2WidthContstraint:NSLayoutConstraint! // outlet for equal widths constraint for button2.

    override func viewDidLoad() {
        super.viewDidLoad()
        button2WidthContstraint.constant = 50 -  self.view.bounds.size.width;
        setUpTimer()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setUpTimer() {
        Timer.scheduledTimer(withTimeInterval: 4, repeats: false) {[weak self] (timer) in
            self?.setButtonWidthEqual()
            timer.invalidate()
        }
    }

    func setButtonWidthEqual() {
        button2WidthContstraint.constant = 0
        UIView.animate(withDuration: 0.2) {
            self.view.layoutIfNeeded()
        }
    }

}

<强>输出

enter image description here

答案 1 :(得分:0)

 /*
         Add Button 1 from storyboard and add constraints: (left:0, top: 0)
         Add Button 2 from storyboard and add constraints: (left:10, right 0, width: 44) (Initial width)
         Now made out let of Button_2's width

         The place where u need to make the width of both button same write the following code.
         */

        self.button2Width.constant = (self.view.frame.size.width-10)/2
        UIView.animate(withDuration: 0.2) { 
            self.view.layoutIfNeeded()
        }

        /*
         we reduce 10 from total view width because there is only 10 point space in both buttons & there is no leading trailing space.
         means zero leading trailing space. 
         -> If you specify any leading trailing space then minus that space from total width.
         */