自定义UIVIEW没有显示?错误的“ override init()”?

问题描述 投票:0回答:1

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

我如何初始化视图:

    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类:

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
    }
}
swift uiview custom-view
1个回答
0
投票

您正在混淆视图的framebounds

视图的frame是其父级坐标系内的坐标。视图的frame是其在自己的坐标系内的坐标。

[当您使用图层和路径绘制东西时,所有内容都是相对于视图的坐标系的,因此您应该使用bounds,而不是bounds。绘制时,视图的父项是无关紧要的。

bounds

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

frame
© www.soinside.com 2019 - 2024. All rights reserved.