我有一个 tableviewcell,它在 stackview 中有两个按钮。其中一个按钮名称是 topupButton,另一个是详细信息按钮。如果一个标志为真,则顶部按钮隐藏。您可以在下面找到代码。
self.topupButton.isHidden = self.selectedSim.operator_?.is_prepaid ?? false
当我隐藏 topup 按钮时,详细信息按钮应该在 stackview 中拉伸(stretch)。但是在我的一个牢房中,它的尺寸不正确。当我进行可视化调试时,我看到按钮的框架是正确的,但背景没有穿过按钮。您可以在下面看到图像。
我已经尝试过 layoutsubviews、setneedsdisplay、layoutifneeded for cell、stackview 和按钮。没有改变。您还可以在下面找到我的堆栈 View 配置。
最佳答案
根据您的评论,很明显 UIBeizerPath
的使用首先造成了问题。这是因为:
Auto-Layout works best with
UIView
. But layers don't auto-resize.
看this question & answer有关以上内容的更多信息。
由于您可能会向按钮添加 mask 层,因此您需要找到添加 mask 层的理想方法。并根据this answer , 正确的位置是 draw(_:) .所以基本上你会做如下的事情:
class TableViewCell: UITableViewCell {
. . .
override func draw(_ rect: CGRect) {
super.draw(rect)
topupButton.roundButton()
detailsButton.roundButton()
}
. . .
}
// extension for rounding button with UIBezierPath
extension UIButton {
func roundButton(){
let size = CGSize(width: bounds.width / 2, height: bounds.width / 2)
let maskPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: .allCorners,
cornerRadii: size)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
}
}
关于ios - 在 stackview 中隐藏按钮会破坏 tableview 中的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59451722/