簡體   English   中英

如何在UICollectionView加載時選擇單元格

[英]How to select cell on UICollectionView load

我正在加載一個收集視圖,在該視圖中,單元格被選中時,單元格將在視圖上繪制一個圓圈(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中調用它。

關於如何選擇負載單元的任何建議都將很棒! 謝謝。

您應該使用selectedBackgroundView指示對cell選擇。 這是該屬性的描述:

如果selectedBackgroundViewbackgroundView不同,它將被放置在背景視圖上方,並在選擇時進行動畫處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM