gpt4 book ai didi

uicollectionview - 拖动 UICollectionViewCell 时如何实现透明背景或圆角

转载 作者:行者123 更新时间:2023-12-03 20:52:38 38 4
gpt4 key购买 nike

我确信一定有一种简单的方法可以做到这一点,但到目前为止,我已经花了很长时间在各种兔子洞中没有成功。

我有一个支持拖放的 Collection View 。被拖动的单元格有 UIImageViewcontentView ,并且 ImageView 的支持层应用了圆角半径。单元格中所有 View 的背景颜色清晰。

拖动时,单元格具有白色背景,显示在 ImageView 的角落周围:

white backgrounds when dragging cell

有没有办法将整个可拖动 View 四舍五入?或将其背景设置为清除以使烦人的白色边框不可见?

更新

事实证明,解决方案非常简单(假设 UIBezierPaths 符合您对简单的定义):

您需要覆盖 collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) UICollectionViewDragDelegate 的方法协议(protocol),并返回 UIDragPreviewParameters使用适当的 UIBezierPath 集:

func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
let previewParams = UIDragPreviewParameters()

let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 140, height: 140), cornerRadius: 20)
previewParams.visiblePath = path

return previewParams
}

这是一个简单的实现,它硬编码 CGRect从中派生贝塞尔路径 - 这适用于我的场景,因为所有单元格的大小相同。更复杂的 Collection View 需要在这里进行一些自定义计算。

enter image description here

最佳答案

我认为这甚至比这更容易。如果你的单元格已经有一个清晰的背景和一个圆角的 UIImageView,你只需要设置 backgroundColor.clear对于 UIDragPreviewParameters .

func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? {
let params = UIDragPreviewParameters()
params.backgroundColor = .clear
return params
}
编辑:根据要求,这是单元格的精简版本
final class MyCell: UICollectionViewCell {
// MARK: Constants

private enum Constants {
static let cornerRadius = CGFloat(8)
}

// MARK: Views

private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = Constants.cornerRadius
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()

// MARK: Lifecycle

override init(frame: CGRect) {
super.init(frame: frame)
setup()
}

required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}

override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}

// MARK: Public

func update(with image: UIImage) {
imageView.image = image
}

// MARK: Private

private func setup() {
contentView.backgroundColor = .clear

contentView.addSubview(imageView)

NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])
}
}

关于uicollectionview - 拖动 UICollectionViewCell 时如何实现透明背景或圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62177637/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com