自定义 UIVIEW 未显示?错了"override init()"?

Custom UIVIEW is not showing up? Wrong "override init()"?

我尝试创建某种工具提示。但我想我在初始化部分做错了什么。为什么我的工具提示没有显示在视图中?我不能像这样使用 override init 吗?

我如何初始化视图:

    let test = ToolTipView(frame: CGRect(x: self.view.center.x , y: self.view.center.y, width: self.view.frame.size.width, height: 50))
    self.view.addSubview(test)

这是我的自定义 UIView Class:

import UIKit

class ToolTipView: UIView {

    let tipOffset : CGFloat = 10.0

    override init(frame: CGRect) {
        super.init(frame: frame)

        print(frame)

        let mainRect = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height - tipOffset)
        let roundRectBez = UIBezierPath(roundedRect: mainRect, cornerRadius: 3.0)
        let mainShape = CAShapeLayer()
        mainShape.path = roundRectBez.cgPath
        mainShape.fillColor = darkGray.cgColor
        self.layer.addSublayer(mainShape)

        let trianglePath = createTip(_frame: frame)
        self.layer.insertSublayer(trianglePath, at: 0)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func createTip(_frame: CGRect) -> CAShapeLayer{
        let shape = CAShapeLayer()

        let tipRect = CGRect(x: _frame.minX, y: _frame.minY, width: _frame.width, height: _frame.height - tipOffset)

        let path = UIBezierPath()
        path.move(to: CGPoint(x: tipRect.midX - 10, y: tipRect.maxY))
        path.addLine(to: CGPoint(x: tipRect.midX, y: tipRect.maxY + tipOffset))
        path.addLine(to: CGPoint(x: tipRect.midX + 10, y: tipRect.maxY))
        path.addLine(to: CGPoint(x: tipRect.midX - 10, y: tipRect.maxY))
        path.close()

        shape.path = path.cgPath
        shape.fillColor = darkGray.cgColor

        return shape
    }
}

您混淆了视图的 framebounds

视图的frame of the view is its coordinates within its parent's coordinate system. The bounds是它在自己的坐标系中的坐标。

当你用图层和路径绘制东西时,一切都是相对于视图的坐标系,所以你应该使用 bounds,而不是 frame。当您绘制时,视图的父视图是无关紧要的。

override init(frame: CGRect) {
    super.init(frame: frame)

    print(frame)

    // changed all "frame" to "bounds"
    let mainRect = CGRect(x: bounds.minX, y: bounds.minY, width: bounds.width, height: bounds.height - tipOffset)
    let roundRectBez = UIBezierPath(roundedRect: mainRect, cornerRadius: 3.0)
    let mainShape = CAShapeLayer()
    mainShape.path = roundRectBez.cgPath
    mainShape.fillColor = UIColor.darkGray.cgColor
    self.layer.addSublayer(mainShape)

    // here as well
    let trianglePath = createTip(_frame: bounds)
    self.layer.insertSublayer(trianglePath, at: 0)
}

此外,将视图添加到其父级时,您可能打算使用 0 的 x 坐标,或宽度的一半,否则视图将超出其父级的边界:

let test = ToolTipView(frame: CGRect(x: 0 , y: self.view.center.y, width: self.view.frame.size.width, height: 50))
// or
let test = ToolTipView(frame: CGRect(x: self.view.center.x , y: self.view.center.y, width: self.view.frame.size.width / 2, height: 50))