针对 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()
}
用途:
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 用于测试项目