如何将3个UIButtonalignment到UITableCellView的中心?

我如何将3个UIButtonalignment到UITableCellView的中心?

例如说我有3个标题为UIButton

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

一个或多个UIButton可能被隐藏。 例如,如果电话UIButton被隐藏,那么只有电子邮件和Skype应该在中心alignment。 如果电话和Skype被隐藏,那么只有电子邮件应该在中心alignment。

当任何UIButton被隐藏时,可见的应该在中心alignment。

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

testingxcode 7:

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

在这里输入图像说明

解:

在这里输入图像说明

步骤: 1)需要的是一个封装视图,它把所有三个button(Skype,电话,电子邮件)放在中间,而不pipe是否有一个button,两个或三个里面。 为此,创build一个持有者视图,在下面的快照中以绿色背景显示。 在这里输入图像说明

那持有者观点的限制是

在这里输入图像说明

它只是保存所有的子视图,它将从其内容中获得它的大小,所以不需要给它的高度/宽度的限制。

2)现在在中心button的约束将是

在这里输入图像说明

3)任何一方的button限制

在这里输入图像说明

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

对于TableView Cell:

  @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() } 

使用:

  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! } 

用UIStackView可以达到同样的效果(显然没有这么头痛),但是在9.0之前的iOS上不能运行

更新(2015年10月26日):

GitHub Repo用于testing项目

你应该看看UIStackView(但是,它是iOS 9的)。

我相信有一个UIStackViews的方法,其中embedded的UIViews“消失”,它将重新alignmentembedded在同一个UIStackView中的其他UIViews。