![](/img/trans.png)
[英]UICollectionViewCell rounded corners revert to square when breathed upon
[英]How to achieve transparent background or rounded corners when dragging a UICollectionViewCell
我確信一定有一種簡單的方法可以做到這一點,但是到目前為止,我已經花了很長時間在各種兔子洞中沒有成功。
我有一個支持拖放的集合視圖。 被拖動的單元格在contentView
中有一個UIImageView
,並且圖像視圖的支持層應用了角半徑。 單元格中所有視圖的背景顏色清晰。
拖動時,單元格具有白色背景,顯示在圖像視圖的角落周圍:
有沒有辦法將整個可拖動視圖四舍五入? 或將其背景設置為清除以使煩人的白色邊框不可見?
更新
事實證明,解決方案非常簡單(假設UIBezierPaths
符合您對簡單的定義):
您需要覆蓋UICollectionViewDragDelegate
協議的collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath)
方法,並返回帶有相應UIDragPreviewParameters
集的 UIDragPreviewParameters:
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
進行硬編碼 - 這適用於我的場景,因為所有單元格的大小都相同。 更復雜的集合視圖需要在這里進行一些自定義計算。
我認為這甚至比這更容易。 如果你的單元格已經有一個清晰的背景和一個圓角 UIImageView,你只需要為UIDragPreviewParameters
設置backgroundColor
為.clear
。
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),
])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.