如何解决更改 CollectionView Cell 内的 UIView 宽度
我将 UIView "statusbar
" 作为我的单元格内的背景,它的工作原理类似于进度条。橙色视图是状态栏:
问题
当我启动应用程序时,状态栏正在上升以供演示使用。但是之后(在 layoutSubviews()
中设置后)我无法更改状态栏的宽度。
这是我的单元格类代码:
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var statusbar: UIView!
var newWidth = 0
override func layoutSubviews() {
self.layer.cornerRadius = 15.0
self.layer.masksToBounds = true
statusbar.frame = CGRect(x: 0,y: 0,width: newWidth,height: Int(self.frame.height))
super.layoutSubviews()
}
}
extension MyCollectionViewCell{
func setStatusbar(completedTasks: Int,totalTasks: Int){
newWidth = Int((Double(self.frame.width) * (Double(completedTasks) / Double(totalTasks)))) //calculates new width with given tasks
//Local var attempt: (not working)
/**var frameRect = statusbar.frame;
frameRect.size.width = newWidth;
statusbar.frame = frameRect; **/
//Change CGRect attempt: (not working)
statusbar.frame = CGRect(x: 0,height: Int(self.frame.height))
//Somehow update the cells... should call layoutSubviews here?
reloadInputViews()
}
}
在我的 ViewController.swift 中,我将状态栏宽度更改为 cell.setStatusbar(completedTasks: indexPath.row,totalTasks: 47)
以下是 ViewController.swift 中的两个重要函数,我想从中更改状态栏:
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,for: indexPath as IndexPath) as! MyCollectionViewCell
cell.myLabel.text = self.items[indexPath.row]
cell.backgroundColor = UIColor(rgb: 0xF444444)
cell.setStatusbar(completedTasks: indexPath.row,totalTasks: 47) //Makes the statusbar increasing with every cell for testing when launched
return cell
}
func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {
// handle tap events
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,for: indexPath as IndexPath) as! MyCollectionViewCell
cell.setStatusbar(completedTasks: 47,totalTasks: 47) //Should make the statusbar to 100% (equal width as cell) for testing!
collectionview.reloadData()
}
有人可以帮助我...我只是无法更改“状态栏”(橙色 UIView)的使用:/
谢谢!
解决方法
不要在 collectionview.reloadData()
中调用 didSelectItemAt
,因为这会导致所有单元格自行重新加载并将 completedTasks
设置回 indexPath.row
调用 setStatusBar
或调用 layoutSubviews
后,您不应该需要重新加载集合视图(无论如何您都不应该直接调用它,您应该使用 setNeedsLayout
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。