如何居中两个标签

我有两个button。 我想同时在同一行上的两个button水平,我想在左边的button左边,两个button之间,右边的右边button相等的空间。

我想要居中这样的两个button:

在这里输入图像说明

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

以编程方式制作UIButton

在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到居中,居中的宽度为父。

例:

 Parent Width: 320 let widthBlock = 320/2 block 1: x = 0, width = widthBlock block 2: x = widthBlock, width = widthBlock 

然后在每个块中创buildbutton,并使用约束来垂直和水平居中。

正如你在界面上做的那样简单得多,只需从button拖动到块,然后Center Horizontal in Container其父Center Horizontal in ContainerCenter vertically in container

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

  • 添加约束来设置所有的空间视图等宽,固定高度(例如:30)。
  • 将空间视图和button之间的约束拟合空间添加到0,将超视图的空间视图添加到0。
  • 为ce​​nterY添加所有空间视图和button的约束。
  • 将约束添加到顶级超级视图。

当完成视图的样子

在这里输入图像说明

这个问题最简单的方法之一就是使用spacer视图。

在这里输入图像说明

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

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

以下是不同屏幕的输出:

在这里输入图像说明

注意:由于空间限制,5.5屏幕不包括在内,但也可以在5.5屏幕上查看,也可以使用。