我尝试创建某种工具提示。但是我想我在初始化部分做错了。为什么我的工具提示没有显示在视图中?不能我这样使用覆盖初始化吗?
我如何初始化视图:
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
}
}