遊戲推薦展示
展示效果
- 展示效果
思路分析
- 其實這個實現比較簡單,也是有兩種方案
- UIScrollView:直接在上面放上UIButton即可
- UICollectionView:每一個遊戲用一個Cell來展示
- 方案選擇
- 方案二:UICollectionView來實現
- 一方面可以循環利用,另一方面UICollectionView真的非常好用喔
界面搭建
- 自定義RecommendGameView
- 由於內容比較固定,直接通過xib描述
- 添加UICollectionView即可
- 設置UICollectionView的佈局,設置數據源以及實現數據源方法(見代碼)
- 切記:設置自定義View的autoresizingMask = .None,否則控件將不能顯示
class RecommendGameView: UIView {
// MARK: 控件屬性
@IBOutlet weak var collectionView: UICollectionView!
// MARK: 系統回調
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = .None
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: kGameCellW, height: kGameViewH)
collectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
}
// MARK:- 提供快速創建的類方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return NSBundle.mainBundle().loadNibNamed("RecommendGameView", owner: nil, options: nil).first as! RecommendGameView
}
}
// MARK:- 遵守UICollectionView的數據源&代理
extension RecommendGameView : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kGameCellID, forIndexPath: indexPath) as! CollectionGameCell
cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.blueColor()
return cell
}
}
-
將自定義View添加到UICollectionView中
- 懶加載RecommendGameView對象
- 將gameView添加到UICollectionView中
- 設置UICollectionView的內邊距
- 代碼如下:
-
懶加載RecommendCycleView
private lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
- 添加UIContentView中
collectionView.addSubview(gameView)
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
展示數據
- 因爲該位置展示的數據,其實是請求熱門遊戲中10組數據,因此直接展示即可
- 將之前請求到的groups數組,傳遞給gameView
- 對數據進行進一步處理
- 將前兩組數組刪除(熱門、顏值)
- 在最後添加更多分組(最後有一組更多)
- 對數據進行進一步處理
- 自定義Cell,用於展示數據
- 通過Xib直接描述
- 通過Xib直接描述
- 根據模型展示數據
- 代碼如下
class CollectionGameCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
var group : AnchorGroup? {
didSet {
let iconURL = NSURL(string: group?.icon_url ?? "")!
iconImageView.kf_setImageWithURL(iconURL, placeholderImage: UIImage(named: "home_more_btn"))
titleLabel.text = group?.tag_name
}
}
override func awakeFromNib() {
super.awakeFromNib()
iconImageView.layer.cornerRadius = iconImageView.bounds.width * 0.5
iconImageView.layer.masksToBounds = true
}
}