ios - 在 stackview 中隐藏按钮会破坏 tableview 中的布局

标签 ios swift uitableview uistackview

我有一个 tableviewcell,它在 stackview 中有两个按钮。其中一个按钮名称是 topupButton,另一个是详细信息按钮。如果一个标志为真,则顶部按钮隐藏。您可以在下面找到代码。

  self.topupButton.isHidden = self.selectedSim.operator_?.is_prepaid ?? false

当我隐藏 topup 按钮时,详细信息按钮应该在 stackview 中拉伸(stretch)。但是在我的一个牢房中,它的尺寸不正确。当我进行可视化调试时,我看到按钮的框架是正确的,但背景没有穿过按钮。您可以在下面看到图像。

Two button cell

What I want when hide the topupbutton

When I hide the button

我已经尝试过 layoutsubviews、setneedsdisplay、layoutifneeded for cell、stackview 和按钮。没有改变。您还可以在下面找到我的堆栈 View 配置。

Stackview config

Constraint of stackview

Constraint of stackview

Layout of cell

最佳答案

根据您的评论,很明显 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/

相关文章:

swift - 指定表页脚时,最后一个单元格缺少 uitableview 分隔符

ios - 我如何从字符串中获取一个整数?

iphone - UIView 在 UITableViewController 的中心

iphone - 如何将UITabbar连接到ViewController

ios - UITextView 表情符号字符限制计数不正确

iphone - 如何从 Facebook 中退出我的 iOS 应用程序 - 就像真的退出一样。 iOS 设备使用我的应用无法忘记的 Safari cookie

SwiftUI 从 String(Base64) 解码图像

ios - Xcode 6 创建 Storyboard警告

ios - 在带有分页的 ScrollView 中拥有多个 tableView 会使 tableHeaderView 的 searchBar 不可触摸

ios - cocoa : Why is my table view blank?