swift - 圆角tableview标题swift
问题描述
我正在尝试在 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, width: 300, 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, width: 300, 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, y: cardRadius),
radius: 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
}
}
推荐阅读
- angular - 如何设置输入角度的默认值?
- android - 如何修复 Retrofit Android Studio 中的 500 响应代码错误
- firebase - 如何在 Firebase 模拟器中存根外部服务?
- javascript - 在 Firestore 中添加新字段
- java - Java 11 的 Evosuite 插件问题
- ebay-api - 如何通过 ItemID Ebay SDK 获取产品列表
- c# - 通过网络分发应用程序时未捕获 FileNotFoundException
- jenkins - 是否可以从 Jenkinsfile 运行 Jenkinsfile
- arrays - Bash脚本 - 函数退出时全局变量变为空
- angular - 在我的服务器上部署 Angular 应用程序似乎没有做任何事情