ios - iOS (9+) 中使用 nibs (.xib) 和 Swift 5/Xcode 11.3 的 View 半径不一致

标签 ios swift xcode

我有一个使用 Xcode 11.3 为 iOS 9.0+ 编译的聊天应用程序,并且想要显示具有 3 个“半径 12”角和一个“半径 3”角的聊天气泡。 View 上的“角半径”设置设置为 3,因此如果没有更改, View 的所有四个角都设置为半径为 3。这些 View 位于 tableView 中的单元格中。正确设置三个较大的半径后,聊天气泡应如下所示:

enter image description here

这是 Nib :

enter image description here

当创建新的聊天气泡并填充文本时,使用 View 扩展添加半径的代码:

@IBDesignable
class ChatSent: NibDesignable {
    @IBOutlet weak var itemText: UILabel!
    @IBOutlet weak var itemBubbleSent: UIView!

    @IBInspectable
    public var Text: String = "" {
        didSet {
            self.itemText.text = Text
            itemBubbleSent.roundSentCorners([.topLeft, .topRight, .bottomLeft], radius: 12)
        }
    }
}

extension UIView {
    func roundSentCorners(_ corners:UIRectCorner, radius: CGFloat) {
    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    self.layer.mask = mask
  }
}

在主视图 Controller 中,聊天气泡中的文本设置如下:
let cell = tableView.dequeueReusableCell(withIdentifier: "Chat Sent", for: indexPath) as! ChatViewSentCellView
cell.myChatViewSent.Text = self.messageData[self.messageIndex!].messages[indexPath.item - 10]

所以,问题是没有正确创建半径角。它们始终不一致,这意味着加载 View 时每个气泡上都会发生相同的错误。此外,通过上下滚动,可以使气泡正确绘制,只有在向上滚动到下一组气泡时才返回到不正确的显示。请注意,有些角的半径错误或没有半径,并且有些气泡偏移了:

chat bubbles not drawn properly

这里发生了什么?

最佳答案

您的问题在于 frame你正在传递给你的函数,因为单元格还没有计算它的布局,你应该做这样的事情:

第一的:

let cell = tableView.dequeueReusableCell(withIdentifier: "Chat Sent", for: indexPath) as! ChatViewSentCellView
cell.myChatViewSent.text = self.messageData[self.messageIndex!].messages[indexPath.item - 10]

然后在您的自定义表格单元格类中:

class CellWithCustomLayout: UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        itemBubbleSent.layoutIfNeeded()
        //Mask your view with the path here, the view has the proper frame now, i.e:
        itemBubbleSent.roundSentCorners([.topLeft, .topRight, .bottomLeft], radius: 12)
    }
}

您可以更改代码以满足您的需要,但通常在 viewDidLayoutSubviews 之后和 layoutSubviews框架已计算并准备好使用。

关于ios - iOS (9+) 中使用 nibs (.xib) 和 Swift 5/Xcode 11.3 的 View 半径不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583775/

相关文章:

arrays - 如何泛化一个参数是具有不同属性的不同结构的函数?

Swift UIImagePickerController didFinishPickingMediaWithInfo 未触发

iphone - 如何在xcode中创建DropDown?

ios - SceneKit 中的 COLLADA 转换

ios - UINavigationController 的 viewControllers 和 childViewControlle 之间的区别

swift - Swift 3 : Cannot convert value of type 'NSMutableDictionary' to expected argument type '[AnyHashable : Any]!'

ios - 为什么 Xcode Variables View "Edit Value"没有改变变量值?

iphone - 如何声明一个 MKPolygon

iOS @2x 适用于非视网膜且无法正确缩放

ios - swift 5 的最低 ios 部署目标是什么?