ios 在swift5中将集合视图的单元格中的行作为边框

h5qlskok  于 2023-03-31  发布在  iOS
关注(0)|答案(1)|浏览(153)

enter image description hereenter image description here
我想在swift中的集合视图的单元格中用灰色做一个边框线

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath
}

     func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        var borderColor: CGColor! = UIColor.clear.cgColor
        var borderWidth: CGFloat = 0

        if indexPath == selectedIndexPath{
            borderColor = UIColor.brown.cgColor
            borderWidth = 1 //or whatever you please
        }else{
            borderColor = UIColor.clear.cgColor
            borderWidth = 0
        }

        cell.layer.borderWidth = borderWidth //You can use your component
        cell.layer.borderColor = borderColor 

   }

I tried this way.
vcirk6k6

vcirk6k61#

尝试这种方法,在viewDidLoad中将collection isPagingEnabled设置为true

YourCollectionView.isPagingEnabled = true

在cellForItemAt中将CONTENTVIEW边框颜色设置为clear,宽度设置为0:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell = YourCollectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuCell
    cell.contentView.backgroundColor = .red
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.borderWidth = 0
    
    return cell
}

现在,在didSelectItemAt中,将所有可见单元格重置为无边框,并仅选择边框:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = YourCollectionView.cellForItem(at: indexPath) as! YourCell
    // set ALL visible cell to no border
    for myCell in YourCollectionView.visibleCells {
        myCell.contentView.layer.borderColor = UIColor.clear.cgColor
        myCell.contentView.layer.borderWidth = 0
    }
    // set ONLY SELECTED CELL border to your prefer color and width
    cell.contentView.layer.borderColor = UIColor.white.cgColor
    cell.contentView.layer.borderWidth = 1
}

现在可以在scrollViewDidScroll方法中检测页面更改并重置边框:

var previousPage: Int = 0
func scrollViewDidScroll(_ scrollView: UIScrollView){
    let pageWidth: CGFloat = scrollView.frame.width
    let fractionalPage: CGFloat = scrollView.contentOffset.x / pageWidth
    let page = lround(Double(fractionalPage))
    if page != previousPage {
        // page changed
        print(page)
        // reset all cells to no border when page changed
        for myCell in YourCollectionView.visibleCells {
            myCell.contentView.layer.borderColor = UIColor.clear.cgColor
            myCell.contentView.layer.borderWidth = 0
        }
    }
}

这就是结果

相关问题