【问题标题】:How to center two labels如何使两个标签居中
【发布时间】:2016-08-01 21:21:29
【问题描述】:

我有两个按钮。我希望两个按钮水平位于同一行,并且我希望左侧按钮左侧、两个按钮之间以及右侧按钮右侧的空间相等。

我想像这样将两个按钮居中:

【问题讨论】:

标签: ios swift xcode autolayout constraints


【解决方案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")
}

【讨论】:

    【解决方案2】:

    当你处理约束时,你必须工作块。

    在这种情况下,您应该有 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

    【讨论】:

      【解决方案3】:

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

      • 添加约束以设置所有空间视图等宽,并固定高度 (例如:30)。
      • 将空间视图和按钮之间的空间适合空间限制添加为 0,并且 超级视图的空间视图为 0。
      • 为所有空间视图和按钮的 centerY 添加约束。
      • 为顶级超级视图添加约束。

      完成后的样子

      【讨论】:

        【解决方案4】:

        解决此问题的最简单方法之一是使用间隔视图。

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

        在这里,我采取了容器视图。不需要的可以忽略。

        这是不同屏幕的输出:

        注意:由于篇幅限制,这里不包括5.5屏幕,但你也可以签入5.5屏幕,它会工作。

        【讨论】:

          猜你喜欢
          • 2013-11-12
          • 2014-05-29
          • 2020-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-21
          • 1970-01-01
          相关资源
          最近更新 更多