问题描述
我正在尝试在 tableview 顶部添加一个圆形 tableview 标题。它的顶部位于图像下方:
所以我的想法是绘制一个形状视图并将此视图添加为标题。 但是从我看到的解决方案来看,我所能做的就是这种形状:
我的问题是:如何在没有额外高度的情况下拥有这种观点?所以没有低于角落的高度。 任何其他实现设计的方式也不错。
我的代码:
import UIKit
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0,y: 0,width: 300,height: 500))
containerView.backgroundColor = .white
PlaygroundPage.current.liveView = containerView
let headerView = UIView()
let frame2 = CGRect(x: 0,y: 190,height: 40)
headerView.clipsToBounds = true
headerView.backgroundColor = .red
headerView.frame = frame2
headerView.roundCorners([.topLeft,.topRight],radius: 40)
containerView.addSubview(headerView)
extension UIView {
func roundCorners(_ 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
}
}
解决方法
我找到了一个方法:
import UIKit
import PlaygroundSupport
let containerView = UIView(frame: CGRect(x: 0,y: 0,width: 300,height: 500))
containerView.backgroundColor = .white
PlaygroundPage.current.liveView = containerView
let headerView = UIView()
let frame2 = CGRect(x: 0,y: 190,height: 22)
headerView.clipsToBounds = true
headerView.backgroundColor = .red
headerView.frame = frame2
draw(shapeView: headerView)
containerView.addSubview(headerView)
func draw(shapeView:UIView) {
let path = headerView.headerBezierPath(hight: headerView.frame.height).cgPath
let shape = CAShapeLayer()
shape.path = path
shapeView.layer.mask = shape
}
extension UIView {
func headerBezierPath(hight:CGFloat) -> UIBezierPath {
let cardRadius = CGFloat(hight)
let viewSize = self.bounds.size
let path = UIBezierPath()
path.move(to: CGPoint(x: cardRadius,y: 0))
// top line
path.addLine(to: CGPoint(x: viewSize.width - cardRadius,y: 0))
// top-right corner arc
path.addArc(withCenter:
CGPoint(x: viewSize.width - cardRadius,y: cardRadius),radius: cardRadius,startAngle: CGFloat(Double.pi * 3 / 2),endAngle: CGFloat(0),clockwise: true)
// bottom line
path.addLine(to: CGPoint(x: 0,y: cardRadius))
// top-left corner arc
path.addArc(
withCenter: CGPoint(x: cardRadius,startAngle: CGFloat(Double.pi),endAngle: CGFloat(Double.pi / 2 * 3),clockwise: true
)
// close path join to origin
path.close()
// Set the background color of the view
UIColor.gray.set()
path.fill()
return path
}
}
,
使用此视图扩展
extension UIView {
func roundCorners(corners: UIRectCorner,radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds,byRoundingCorners: corners,cornerRadii: CGSize(width: radius,height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
扩展名的使用:
viewPopupCard.roundCorners(corners: [.topLeft,.topRight],radius: 18)