我正在制作日历应用程序,自然,我希望一周7天。当前的显示方式是每周显示5天:
这是我的故事板。我已经确保可以容纳7件物品,以符合我想要的方式放置它们。可能与我的问题有关的一件事是,当我添加更多项(单元格)时,它们与第一个项的标识符(日历)不同。
这是我的视图控制器代码:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{
@IBOutlet weak var Calendar: UICollectionView!
@IBOutlet weak var MonthLabel: UILabel!
let Months = ["January","February","March","April","May","June","July",
"August","September","October","November","December"]
let DaysOfMonth = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"]
let DaysInMonths = [31,28,31,30,31,30,31,31,30,31,30,31]
var currentMonth = String()
override func viewDidLoad() {
super.viewDidLoad()
currentMonth = Months[month]
MonthLabel.text = "\(currentMonth) \(year)"
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return DaysInMonths[month]
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Calendar", for: indexPath) as! DateCollectionViewCell
cell.backgroundColor = UIColor.clear
cell.DateLabel.text = "\(indexPath.row + 1)"
return cell
}
}
回顾一下:我希望收藏视图中连续有7个项目,但目前有5个。我试图更改情节提要中的间距以及收藏视图单元格的标识符。
Try specifying the size for item at indexPath, to do that make sure you have set self.calendar.delegate = self
and then add an extension to your ViewController
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.calendar.bounds.size.width / 7, height: your_cell_height)
}
}
This will work assuming you haven't specified any spacing between the cells, if you have specified spacing between the cells make sure you account it as well in your calculation.
For example: if you want spacing between cells (horizontally) be 10
calculation will change to
(self.calendar.bounds.size.width / 7) - 60)
why 60? ( 6 spaces between 7 cells each of size 10 so 6 * 10)
Finally, why is it showing 7 cells in XIB and not in real device/ simulator? XIB's screen width might be different from the device screen width, you can drag Xib to required width to accommodate as many cells as you want horizontally, that does not guarantee that when app runs in real device it gets the similar real estate.
它是一种流布局,因此内容会流,当它意识到没有更多空间可容纳一行中的更多单元格时,内容(单元格)会流到下一行,希望可以澄清问题
PS:切勿使用Pascal大小写(第一个字母为大写)来命名变量,请@IBOutlet weak var Calendar: UICollectionView!
始终使用Camel大小写更改为@IBOutlet weak var calendar: UICollectionView!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句