我已经尝试了一段时间,但是我已经筋疲力尽了。我一直在尝试将CAShapeLayer添加到自定义UICollectionViewCell中,但是它要么不会绘制,要么有时只会绘制。我决定使用以下代码简化我遇到的问题:
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cell"
let dataSource: [UIColor] = [.blue, .purple, .brown, .green, .red]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.isPagingEnabled = true
collectionView.register(CellSubclass.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CellSubclass
cell.backgroundColor = dataSource[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
}
class CellSubclass: UICollectionViewCell {
let circle = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
circle.frame = bounds
let circleCenter = self.center
let path = UIBezierPath(arcCenter: circleCenter, radius: 100, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
circle.path = path.cgPath
circle.fillColor = UIColor.gray.cgColor
layer.addSublayer(circle)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我的UICollectionViewController具有以下流程布局
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
let home = ViewController(collectionViewLayout: layout)
基于我所看到的其他StackOverflow问题,人们建议采用一种方法,在初始化时将形状子层添加到自定义UICollectionViewCell中,就像我完成的那样。但是,当我运行此代码时,得到以下输出:
我们非常感谢您了解如何解决此问题,以使自定义单元格的每个实例都具有自己的形状。
更改
let circleCenter = self.center
至
let circleCenter = CGPoint(x:self.bounds.midX, y:self.bounds.midY)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句