gpt4 book ai didi

Swift:UICollectionViewCell - 关闭 UICollectionView

转载 作者:行者123 更新时间:2023-11-28 07:46:36 27 4
gpt4 key购买 nike

尝试通过点击 Collection View 中的单元格来关闭滑入式 UICollectionView。我可以通过使用关闭功能在 Collection View 外部点击来关闭。谢谢

更新:找到了使用委托(delegate)的解决方案。我已经用解决步骤标记了部分代码。

在下面找到我的代码。

家庭 Controller :

        import UIKit

class HomeController: UIViewController, UICollectionViewDelegate , UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

let userInfoCell = "userInfoCell"
let dashboardCell = "dashboardCell"


override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .cyan
setupViews()
}

func setupViews() {
view.addSubview(mainCollectionView)
mainCollectionView.dataSource = self
mainCollectionView.delegate = self

mainCollectionView.register(UserInfoCell.self, forCellWithReuseIdentifier: userInfoCell)
mainCollectionView.register(DashboardCell.self, forCellWithReuseIdentifier: dashboardCell)
}

let mainCollectionView: UICollectionView = {

let windowWidth = UIScreen.main.bounds.width
let windowHeight = UIScreen.main.bounds.height
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 16
layout.scrollDirection = .vertical
let mainCV = UICollectionView(frame: .zero, collectionViewLayout: layout)
mainCV.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 20, height: UIScreen.main.bounds.height - 20)
mainCV.center = CGPoint(x: windowWidth - (windowWidth / 2), y: windowHeight - (windowHeight / 2))
mainCV.backgroundColor = .red

mainCV.layer.cornerRadius = 25
return mainCV
}()

func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 1 {
return 1
}
return 2
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: dashboardCell, for: indexPath) as! DashboardCell
cell.plusButton.addTarget(self, action: #selector(plusButtonPressed), for: .touchUpInside)
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userInfoCell, for: indexPath) as! UserInfoCell
return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: (view.frame.width / 3) - 30 , height: 100)
}
return CGSize(width: (view.frame.width / 2) - 30 , height: 200)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
if section == 1 {
return UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)
}
return UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)
}

@objc func plusButtonPressed() {
print("Plus button pressed")
taggObjectLauncher.showSlideInImages()

}

lazy var taggObjectLauncher: SlideInViewLauncher = {
let launcher = SlideInViewLauncher()
launcher.homeController = self
return launcher
}()

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

class UserInfoCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .blue
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

class DashboardCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .green
setupDashboardViews()
}

func setupDashboardViews() {
addSubview(plusButton)
}

let plusButton: UIButton = {
let button = UIButton()
button.backgroundColor = .yellow
button.setTitle("Plus", for: .normal)
button.setTitleColor(.black, for: .normal)
button.setTitleColor(.gray, for: .highlighted)
button.titleLabel?.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
button.frame = CGRect(x: 5, y: 5, width: (UIScreen.main.bounds.width / 3) - 40, height: 90)
return button
}()

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

SlideInViewLauncher Controller :

        import UIKit

class SlideInViewLauncher: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

var imageCategories: [ImageCategory]?

var homeController = HomeController()

var imageCell = ImageCell()

private let cellIdentifier = "ImageCell"


let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.white

return cv

}()

let blackView = UIView()

@objc func showSlideInImages() {

blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)

if let window = UIApplication.shared.keyWindow {
blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))

let height = CGFloat(450)
let y = window.frame.height - height

collectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)

collectionView.register(SlideInViewCell.self, forCellWithReuseIdentifier: cellIdentifier)

window.addSubview(blackView)
window.addSubview(collectionView)
blackView.frame = window.frame
blackView.alpha = 0

imageCategories = ImageCategory.sampleImageCategories()

UIView.animate(withDuration: 0.5) {
self.blackView.alpha = 1
self.collectionView.frame = CGRect(x: 0, y: y, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}
}
}

@objc func handleDismiss() {
UIView.animate(withDuration: 0.5, animations: {
self.blackView.alpha = 0
if let window = UIApplication.shared.keyWindow {
self.collectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}
})
}

public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selected")

}

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = imageCategories?.count {
return count
}
return 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! SlideInViewCell

cell.imageCategory = imageCategories?[indexPath.row]

///////////////
// Solution: Part 5

cell.cellDelegate = self
///////////////

return cell
}

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width , height: 200)
}

override init() {
super.init()

collectionView.dataSource = self
collectionView.delegate = self
}
}

////////////
// Solution: Part 4

extension SlideInViewLauncher: MyCustomCellDelegate {
func didPressButton() {
UIView.animate(withDuration: 0.5, animations: {
self.blackView.alpha = 0
if let window = UIApplication.shared.keyWindow {
self.collectionView.frame = CGRect(X: 0, y: window.frame.height, width:
self.collectionView.frame.width, height:
self.collectionView.frame.height)

}
})
}
}

/////////////

SlideInViewCell Controller :

       import UIKit

////////////////
//Solution: Part 1

protocol MyCustomCellDelegate: class {
func didPressButton()
}

/////////////

class SlideInViewCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

/////////////////
// Solution: Part 2

weak var cellDelegate: MyCustomDelegate?

////////////////

var homeViewController = HomeController()

var slideInViewLauncher = SlideInViewLauncher()

var imageCategory: ImageCategory? {
didSet {
if let name = imageCategory?.name {
mainCategoryLabel.text = name
}
}
}

var image: Image?

private let cellID = "objectCellID"

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

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

let mainCategoryLabel: UILabel = {
let label = UILabel()
label.text = ""
label.font = UIFont.systemFont(ofSize: 16)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()

var slideInImagesCollectionView: UICollectionView = {

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView

}()

let dividerLineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()

func setupViews() {
backgroundColor = UIColor.clear

addSubview(slideInImagesCollectionView)
addSubview(dividerLineView)
addSubview(mainCategoryLabel)

slideInImagesCollectionView.dataSource = self
slideInImagesCollectionView.delegate = self

slideInImagesCollectionView.register(ImageCell.self, forCellWithReuseIdentifier: cellID)

addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-14-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": mainCategoryLabel]))

addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-14-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": dividerLineView]))

addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": slideInImagesCollectionView]))

addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mainCategoryLabel(30)][v0][v1(0.5)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": slideInImagesCollectionView, "v1": dividerLineView, "mainCategoryLabel": mainCategoryLabel]))
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = imageCategory?.images?.count {
return count
}
return 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! ImageCell
cell.image = imageCategory?.images?[indexPath.item]
return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: frame.height - 30)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(35, 10, 10, 10)
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let imageSelected = imageCategory!.images?[indexPath.item]
print(imageSelected?.name ?? "Error: No item at index path")

//////////////////
// Solution: Part 3

cellDelegate?.didPressButton()

//////////////////
}
}

class ImageCell: UICollectionViewCell {

var image: Image? {
didSet {
if let name = image?.name {
nameLabel.text = name
}

if let imageName = image?.imageName {
imageView.image = UIImage(named: imageName)
}
}
}

override init(frame: CGRect) {
super.init(frame: frame)
setupViews()

}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

let imageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.layer.masksToBounds = true
return iv
}()

let nameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14)
label.numberOfLines = 2
label.textAlignment = .center
return label
}()

func setupViews() {
addSubview(imageView)
addSubview(nameLabel)

imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: 100)
nameLabel.frame = CGRect(x: 0, y: frame.width + 2, width: frame.width, height: 40)
}
}

模型 Controller :

        import UIKit

class ImageCategory: NSObject {

var name: String?
var images: [Image]?

static func sampleImageCategories() -> [ImageCategory] {

var someImages = [Image]()

let someImageCategory = ImageCategory()
someImageCategory.name = "Some Category"

let heartImage = Image()
heartImage.name = "Heart"
heartImage.imageName = "heart"
heartImage.category = "Some Category"

someImages.append(heartImage)

someImageCategory.images = someImages

// Return the array of image categories:

return [someImageCategory]
}
}

class Image: NSObject {

var id: NSNumber?
var name: String?
var category: String?
var imageName: String?
}

最佳答案

能够通过添加委托(delegate)协议(protocol)来解决这个问题。请参阅代码中的注释。另外,很抱歉,如果我的帖子没有完全遵循协议(protocol)。这是我的第一篇文章。

谢谢

关于Swift:UICollectionViewCell - 关闭 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822804/

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