针对 xcode 7 进行测试:
我想你正在寻找类似的东西
解决方案:
Steps:
1) what is needed is an encapsulating view which holds all three buttons (skype, phone, email) into center irrespective of whether there is one button, two or three inside it. For that a holder view is created which is shown with green background in below snapshot.
该持有者视图的约束是
它只是保存所有子视图,它将从其内容中获取其大小,因此不需要给它高度/宽度限制。
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()
}
Use:
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 存储库用于测试项目