如何将3个UIButtons对齐到UITableCellView的中心?

Vik*_*ote 8 uibutton uitableview ios autolayout swift

如何将3 UIButtons与中心对齐UITableCellView

比如说我有3个UIButton标题:

  1. 电子邮件
  2. 电话
  3. Skype的

UIButton可以隐藏一个或多个s.例如,如果UIButton隐藏了电话,那么只有电子邮件和Skype应该在中心对齐.如果隐藏了电话和Skype,那么只有电子邮件应该在中心对齐.

当任何UIButtons被隐藏时,可见的s应该在中心对齐.

我想将它们水平和垂直居中.

Usa*_*ama 21

测试xcode 7:

我想你正在寻找类似的东西

在此输入图像描述

解:

在此输入图像描述

步骤: 1)需要的是一个封装视图,它将所有三个按钮(Skype,电话,电子邮件)保存到中心,而不管是否有一个按钮,其中有两个或三个按钮.为此创建了一个持有人视图,在下面的快照中以绿色背景显示.在此输入图像描述

该持有人观点的约束是

在此输入图像描述

它只是保存所有子视图,它将从其内容中获取其大小,因此无需给出高度/宽度约束.

2)现在对中心按钮的约束将是

在此输入图像描述

3)任何一方的按钮限制都将是

在此输入图像描述

如果你需要隐藏任何按钮,只需将其宽度约束设为0,所有其他按钮将相应重新排列

对于TableView单元格:

    @IBOutlet weak var emailButtonWidthConstraint : NSLayoutConstraint?
    @IBOutlet weak var phoneButtonWidthConstraint : NSLayoutConstraint?
    @IBOutlet weak var skypeButtonWidthConstraint : NSLayoutConstraint?

    func showButtons(showSkype showSkype : Bool, showEmail : Bool, showPhone : Bool ){
        emailButtonWidthConstraint?.constant = showEmail ? 54.0 : 0.0
        phoneButtonWidthConstraint?.constant = showPhone ? 54.0 : 0.0
        skypeButtonWidthConstraint?.constant = showSkype ? 54.0 : 0.0

        self.layoutIfNeeded()
    }
Run Code Online (Sandbox Code Playgroud)

使用:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as? CustomCell

        if indexPath.row == 0 {
            cell?.showButtons(showSkype: true, showEmail: true, showPhone: true)
        } else if indexPath.row == 1 {
            cell?.showButtons(showSkype: false, showEmail: true, showPhone: true)
        } else if indexPath.row == 2 {
            cell?.showButtons(showSkype: true, showEmail: false, showPhone: true)
        } else if indexPath.row == 3 {
            cell?.showButtons(showSkype: true, showEmail: true, showPhone: false)
        } else if indexPath.row == 4 {
            cell?.showButtons(showSkype: false, showEmail: false, showPhone: true)
        } else if indexPath.row == 5 {
            cell?.showButtons(showSkype: false, showEmail: true, showPhone: false)
        } else if indexPath.row == 6 {
            cell?.showButtons(showSkype: true, showEmail: false, showPhone: false)
        } else {
            cell?.showButtons(showSkype: true, showEmail: true, showPhone: true)
        }

        return cell!
    }
Run Code Online (Sandbox Code Playgroud)

使用UIStackView也可以实现同样的效果(显然没有那么令人头痛)但是在9.0之前的iOS上无法运行

更新(2015年10月26日):

GitHub Repo用于测试项目