【问题标题】:How to select cell on UICollectionView load如何在 UICollectionView 加载时选择单元格
【发布时间】:2015-04-18 16:34:07
【问题描述】:

我正在加载一个集合视图,其中在单元格选择时,单元格会在其视图上绘制一个圆圈(UIView + CGRect)以指示选择。这个集合视图代表一个日历,我希望在最初加载时选择第一个日期。因为我的一生无法正确加载,要么选择的代码没有触发,要么圆圈绘制不正确,因为插座尚未在单元格上初始化(圆圈的位置取决于标签的位置)。

这是我在单元格上的选择方法,在从集合视图数据源中选择单元格时调用:

func select() {
    circleView = UIView(frame: CGRectMake(dateLabel.center.x - (dateLabel.frame.size.width / 2), dateLabel.center.y - (dateLabel.frame.size.height / 2), 40, 40))
    circleView!.layer.cornerRadius = 20
    circleView!.backgroundColor = UIColor.blueColor()
    insertSubview(circleView!, atIndex: 0)

    isCellSelected = true
}

这是我的didSelectItemAtIndexPath 代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "EEEE MMMM dd, yyyy"

    var dateString = ""
    if let newDate = NSCalendar.currentCalendar().dateFromComponents(monthComponentsByDay[indexPath.row]) {
        dateString = dateFormatter.stringFromDate(newDate)
        delegate?.dateSelected(newDate)
    }

    if currentCell != nil {
        currentCell!.deselect()
        currentCell = nil
    }


    dateLabel.text = dateString

    currentCell = collectionView.cellForItemAtIndexPath(indexPath) as? CalendarCollectionViewCell
    currentCellIndex = indexPath.row

    currentCell!.select()
}

我试过collectionView.selectItemAtIndexPath(indexPath:animated:scrollPosition:)然后手动调用代码来选择,但是那个时候单元格还没有完全加载。我尝试在视图控制器的cellForItemAtIndexPathviewDidLoad 中调用它,但没有成功。

任何关于如何选择加载单元格的建议都会很棒!谢谢。

【问题讨论】:

  • 您从哪里获得构建视图的数据?
  • @Mikael 目前是本地存储的 json 文件(测试数据)。

标签: ios iphone swift uicollectionview uicollectionviewcell


【解决方案1】:

您应该使用selectedBackgroundView 来表明您选择了cell。这是该属性的描述:

如果selectedBackgroundViewbackgroundView 不同,它将被放置在背景视图上方并在选择时进行动画处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多