Swift3.0後,就很想學習Swift,有興趣的朋友能夠一塊兒相互學習!數組
//聲明兩個存放字符串的數組 var nowClassName = [String]() var surplusClassName = [String]() 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 = 30 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?.backgroundColor = ColorViewBG self.view.addSubview(collectionView!) saveData() }
//添加數據 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 { return surplusClassName.count } } //分區個數 func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } //自定義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] }else{ cell.label.text = surplusClassName[indexPath.item] } return cell }
HotCell 沒有用xib 有興趣的小夥伴能夠寫下
class HotCell: UICollectionViewCell { var label = UILabel() override init(frame: CGRect) { super.init(frame: frame) label = UILabel.init(frame: self.bounds) self.addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }