UICollectionView實現了一下常見的新聞分類. 附有效果圖swift
近期一直在深刻學習swift,實現了CollectionView item的頭東與刪除,用的都是系統的一些函數方法,看起來比較直觀.數組
第一步:app
class HotViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { //聲明兩個存放字符串的數組 var nowClassName = [String]() var surplusClassName = [String]() //是否排序 var isRank = Bool() var collectionView : UICollectionView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = ColorViewBG let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width:80,height:35) //列間距,行間距,偏移 layout.minimumInteritemSpacing = 15 layout.minimumLineSpacing = 20 layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout) collectionView?.delegate = self collectionView?.dataSource = self; //註冊一個cell collectionView!.register(HotCell.self, forCellWithReuseIdentifier:"HotCell") //註冊區頭 collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "headView") collectionView?.backgroundColor = ColorViewBG self.view.addSubview(collectionView!) let gesture = UILongPressGestureRecognizer(target: self, action: #selector(viewCustom(_ :))) collectionView?.addGestureRecognizer(gesture) saveData() }
func viewCustom(_ longPress:UILongPressGestureRecognizer){ let point:CGPoint = longPress.location(in: longPress.view) let indexPath = self.collectionView?.indexPathForItem(at: point) switch longPress.state { case .began: self.collectionView?.beginInteractiveMovementForItem(at: indexPath!) break case .changed: self.collectionView?.updateInteractiveMovementTargetPosition(point) break case .ended: self.collectionView?.endInteractiveMovement() break default: self.collectionView?.cancelInteractiveMovement() break } }
//添加數據 private func saveData() { nowClassName += ["A-1","A-2","A-3","A-4","A-5","A-6","A-7","A-8","A-9","A-10","A-11"] surplusClassName += ["B-1","B-2","B-3","B-4","B-5","B-6","B-7","B-8","B-9","B-10","B-11"] }
// MARK: 代理 //每一個區的item個數 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return nowClassName.count }else { if !isRank { return surplusClassName.count }else{ return 0 } } } //分區個數 func numberOfSections(in collectionView: UICollectionView) -> Int { if !isRank { return 2 } return 1 } //自定義cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HotCell", for: indexPath) as! HotCell cell.backgroundColor = UIColor.red if indexPath.section == 0 { cell.label.text = nowClassName[indexPath.item] cell.button.addTarget(self, action: #selector(removeItem(_ :)), for: .touchUpInside) cell.button.tag = indexPath.row cell.button.isHidden = !isRank }else{ cell.label.text = surplusClassName[indexPath.item] cell.button.isHidden = true } return cell } func removeItem(_ button:UIButton){ //執行在這裏的時候,顯示的是有個分區,不然崩潰,報不明錯誤!,研究過的能夠告訴一下,不勝感激!!! self.collectionView?.performBatchUpdates({ //數據變動 let item = self.nowClassName[button.tag] self.nowClassName.remove(at: button.tag) self.surplusClassName.append(item) let indexPath = IndexPath.init(item: button.tag, section: 0) print(indexPath) let arr:[IndexPath] = [indexPath] self.collectionView?.deleteItems(at: arr) }, completion: { (completion) in self.collectionView?.reloadData() }) } //是否能夠移動 func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { if isRank { return true } return false } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //獲取當前 item //collectionView.cellForItem(at: indexPath) //獲取全部的item //collectionView.indexPathsForVisibleItems if !isRank && indexPath.section == 1{ //先把數據更新好,由於移動後界面會自動刷新,不然會崩潰 nowClassName.append(surplusClassName[indexPath.item]) surplusClassName.remove(at: indexPath.item) let indexPath1 = NSIndexPath.init(item: nowClassName.count-1, section: 0) let indexPath2 = NSIndexPath.init(item: indexPath.item, section: 1) //從當前位置移動到新的位置 collectionView.moveItem(at: indexPath2 as IndexPath, to: indexPath1 as IndexPath) } } //設置拖動(手勢拖動觸發) func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { // if sourceIndexPath.section == 0 && destinationIndexPath.section == 0 { // collectionView.exchangeSubview(at: sourceIndexPath.item, withSubviewAt: destinationIndexPath.item) // } } //區頭設置 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // //區頭 var headerView : UICollectionReusableView? if kind == UICollectionElementKindSectionHeader{ headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headView", for: indexPath) //防止重用,這樣很暴力 for view in (headerView?.subviews)!{ view.removeFromSuperview() } let label = UILabel.init(frame: CGRect(x:20,y:0,width:160,height:30)) if indexPath.section == 0 { label.text = "切換欄目" let button = UIButton.init(type: .custom) button.frame = CGRect(x:collectionView.frame.size.width - 100,y:0,width:80,height:30) button.titleLabel?.textColor = UIColor.cyan button.backgroundColor = UIColor.white let str = isRank ? "完成排序" : "排序刪除" button.setTitle(str, for: .normal) button.setTitleColor(UIColor.red, for: .normal) headerView?.addSubview(button) button.addTarget(self, action: #selector(click(_ :)), for: .touchUpInside) }else if indexPath.section == 1{ label.text = "點擊添加更多欄目" } headerView?.addSubview(label) } return headerView! } func click(_ btn:UIButton){ let str = isRank ? "完成排序" : "排序刪除" btn.setTitle(str, for: .normal) isRank = !isRank print(isRank) self.collectionView?.reloadData() } //設置HeaderView的寬高 //MARK: UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width:collectionView.frame.size.width,height:35) }
HotCell 類的實現ide
class HotCell: UICollectionViewCell { var label = UILabel() var button = UIButton() override init(frame: CGRect) { super.init(frame: frame) label = UILabel.init(frame: self.bounds) label.textAlignment = .center self.addSubview(label) button = UIButton.init(type: .custom) button.backgroundColor = UIColor.white button.frame = CGRect(x:frame.size.width - 20,y:5,width:15,height:15) self.addSubview(button) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }