2016-08-01 54 views
0

我有两个按钮。我想要同一行上的两个按钮水平放置,并且我希望左侧按钮左侧,两个按钮之间以及右侧按钮右侧具有相同的空间。如何居中两个标签

我想中心这样的两个按钮:

enter image description here

+0

可能是这个帮助你... http://stackoverflow.com/questions/32862142/how-to-add-equal-spacing-and-equal-width-for-button-in-ios-auto-布局/ 32862693#32862693或者您可以使用堆栈视图 –

回答

1

如果我是你,我会让他们编程。如果它们包含在视图中,这将起作用。下面的代码假设你想将按钮置于你的viewController中。

使UIButtons编程

在viewDidLoad中:

 let myFirstXCoordinate = CGFloat((self.view.width/4) - (myWidth/2)) 
     let mySecondXCoordinate = CGFloat((3 * self.view.width)/4) - (myWidth/2)) 
     let myWidth:CGFloat = //your button's width 
     let myHeight:CGFloat = //your button's height 
     let myYCoordinate:CGFloat = //your Y Coordinate 

     firstButton.setBackgroundImage(UIImage(named: "myRedOvalThingyImage"), forState: .Normal) 
     firstButton.backgroundColor = UIColor.clearColor() 
     firstButton.frame = CGRectMake(myFirstXCoordinate, myYCoordinate, myWidth, myHeight) 
     firstButton.addTarget(self, action: #selector(ViewController.pressedFirst(_:)), forControlEvents: .TouchUpInside) 
     buttonView.addSubview(firstButton) 

     secondButton.setBackgroundImage(UIImage(named: "myRedOvalThingyImage"), forState: .Normal) 
     secondButton.backgroundColor = UIColor.clearColor() 
     secondButton.frame = CGRectMake(mySecondXCoordinate, myYCoordinate, myWidth, myHeight) 
     secondButton.addTarget(self, action: #selector(ViewController.pressedSecond(_:)), forControlEvents: .TouchUpInside) 
     buttonView.addSubview(secondButton) 

外viewDidLoad中:

func pressedFirst(sender: UIButton!) { 
print("First Oval Thingy Was Pressed") 
} 

func pressedSecond(sender: UIButton!) { 
print("Second Oval Thingy Was Pressed") 
} 
0

当您使用约束时,您必须工作。

在这种情况下,您应该有2个块,它们的大小与从0到居中的中心宽度相同。

例子:

Parent Width: 320 

let widthBlock = 320/2 

block 1: x = 0, width = widthBlock 
block 2: x = widthBlock, width = widthBlock 

然后在每个区块内创建您的按钮,你中心垂直和水平方向上使用约束双方。

由于您对界面做的事情要简单得多,只需将鼠标从按钮上拖拽,然后给他的父亲Center Horizontal in ContainerCenter vertically in container

0

您可以通过向左,中,右添加三个空间视图(UIvews)来实现自动布局。

  • 添加约束条件来设置所有空间视图等宽,并修复高度 (例如:30)。
  • 添加约束介乎spaceview和按钮配空间为0,并且 spaceview与晚饭视图为0
  • 添加约束centerY所有空间视图和按钮。
  • 将约束添加到顶级超级视图。

当完成视图样子

enter image description here

0

一个这个问题最简单的方法是使用间隔意见。

enter image description here

两个红色按钮将具有固定的宽度和三个浅灰色间隔视图也将具有相等的宽度。现在将所有5个组件与相邻组件连接起来。

这里我采取了容器视图。如果你不需要它,你可以忽略它。

这里是在不同的屏幕输出:这里不包括由于空间限制的5.5屏幕,但你可以在5.5屏幕中查看过,它会工作:

enter image description here

注意。