ios - 如何正确地圆化具有动态高度的 TableView 单元格的边缘

标签 ios swift

我的一个表格 View 有问题。我正在为我的应用程序编写一个消息传递页面,该页面使用表格 View 来显示发送和接收的消息。表格单元格需要根据每个单元格的内容更改高度。我的尺寸调整正常,但现在需要将单元格边缘圆化以适应 UI 设计。我过去使用非动态高度完成此操作的方法是调用一个函数来圆化 tableViewCell 中的覆盖函数“layoutSubViews()”中的每个角:

    func roundAllCorners(radius: CGFloat) {
        let allCorners: UIRectCorner = [.topLeft, .bottomLeft, .bottomRight, .topRight]
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: allCorners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }

如果我尝试调用此函数,但单元格的大小是动态调整的,则左边缘会切掉半厘米。如果您将单元格滚动到屏幕外并再次返回,它会修复它。希望你能找到解决我的问题的办法,我的脖子已经痛了一段时间了。谢谢。

最佳答案

您可能还需要重写框架的 setter 并在那里调用它。无论如何,出于多种原因,这都不是一个好主意。问题是 TableView 单元格有许多 View (包括它本身是一个 View ),例如内容 View 和背景 View ......

我建议您在内容 View 上添加另一个 View ,其中包含所有单元格 View 。然后将此 View 作为子类并处理其中的所有舍入。因此,从 Storyboard的角度来看,您会得到如下内容:

- UITableViewCell
    - contentView
        - roundedContainer
            - imageView
            - button
            - label
            ...

圆形 View 具有(或应该具有)约束,因此 layoutSubViews 应足以覆盖以设置角半径。

您可以拥有一个简洁的类,可以用来圆整您的 View ,例如:

class RoundedView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            refresh()
        }
    }
    @IBInspectable var fullyRounded: Bool = false {
        didSet {
            refresh()
        }
    }


    override func layoutSubviews() {
        super.layoutSubviews()
        refresh()
    }

    private func refresh() {
        layer.cornerRadius = fullyRounded ? min(bounds.width, bounds.height) : cornerRadius
    }

}

正如 @iDeveloper 已经提到的,使用图层的 cornerRadius 可能会更好。但如果您需要使用形状图层,您也可以在此类中执行此操作。

确保剪辑此 View 上的边界。

关于ios - 如何正确地圆化具有动态高度的 TableView 单元格的边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54128277/

相关文章:

ios - 无法使用 segue 将数组传递给第二个 View Controller

iOS9 Objective-C 使用定时器在后台运行 GPS

ios - 无法在 SQLite 中找到默认值,swift

ios - 完成 block 问题内的 RxSwift 订阅

swift - libc++abi.dylib : terminating with uncaught exception of type NSException Alamofire

swift - iOS 14 MapKit 选择注解图片bug

ios - 使用 Accelerate Framework 根据 RGB 值修改 Alpha

iOS 应用程序在我的许可证过期后显示 "No longer Available"?

objective-c - nsmutabledictionary 没有可见的接口(interface)声明选择器 setobject :forkey:

ios - 更改 UITableView 中几个选定的表格 View 单元格文本的颜色