今回の内容
- APIで取得した画像をTableViewに表示したCollectionViewCellに表示
コードと簡単解説
- Main.storyboardでViewControllerにTabelViewを作成
Podfile
Podfile
pod 'SwiftyJSON'
pod 'Alamofire'
pod 'SDWebImage'
Model
-
imageURLArrays
の値でCollectionViewCellに画像を表示させます。 -
SearchKeysectionTitle
の値から画像を検索します。
ImageURLModel
import Foundation
struct ImageURLModel{
static var imageURLArrays = [URL]()
static let SearchKeysectionTitle = "cat"
}
- 画像のURLを取得してくる
-
["hits"][getUrlCount]["webformatURL"]
は、["hits"]
のgetUrlCount番目
の["webformatURL"]
を指定しています。
Alamofire
import Foundation
import Alamofire
import SwiftyJSON
class Alamofire{
static func searchGetImageURL(){
AF.request("https://pixabay.com/api/?key=~~~~~APIKey~~~~~&q=\(ImageURLModel.SearchKeysectionTitle)",method: .get,parameters: nil,encoding: JSONEncoding.default).responseJSON { (response) in
switch response.result{
case.success:
ImageURLModel.imageURLArrays = [] //一度、空にする
for getUrlCount in 0...4{
if JSON(response.data as Any)["hits"][getUrlCount]["webformatURL"].string != nil{
ImageURLModel.imageURLArrays.append(URL(string: JSON(response.data as Any)["hits"][getUrlCount]["webformatURL"].string!)!)
}else{ //取得できる"webformatURL"が無くなった時に処理を終わらせる
break
}
}
case .failure:
let error = NSError()
print(error.debugDescription)
break
}
}
}
}
View
TableViewCell
- TableViewのCustomCellを作成します。
-
TableViewCell.xib
にCollectionViewを作成しています。 -
TableViewCell.xib
のIdentifier
にTableViewCellを入力しておきます。 -
.sd_setImage(with: ImageURLModel.imageURLArrays[indexPath.row], completed: nil)
でcellのImageViewに取得してきた画像を表示する。
TableViewCell
import UIKit
import SDWebImage
class TableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
static let identifire = "TableViewCell"
static let nib = {() -> UINib in return UINib(nibName: "TableViewCell", bundle: nil)}
static let collectionViewFlowLayout = UICollectionViewFlowLayout()
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CollectionViewCell.nib(), forCellWithReuseIdentifier: CollectionViewCell.identifire)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension TableViewCell:UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
ImageURLModel.imageURLArrays.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifire, for: indexPath) as! CollectionViewCell
cell.imageView.sd_setImage(with: ImageURLModel.imageURLArrays[indexPath.row], completed: nil)
cell.imageView.contentMode = .scaleAspectFit
return cell
}
}
extension TableViewCell:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.height, height: collectionView.frame.size.height)
}
}
CollectionViewCell
- CollectionViewのCustomCellを作成します。
-
CollectionViewCell.xib
にImageView
を作成しています。
CollectionViewCell
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
static let identifire = "CollectionViewCell"
static let nib = {() -> UINib in return UINib(nibName: "CollectionViewCell", bundle: nil)}
override func awakeFromNib() {
super.awakeFromNib()
}
}
Controller
- Main.storyboardでTableViewを作成しておきます。
ViewController
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.searchGetImageURL() //画像のURLを取得してくる。
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [self] in
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.nib(), forCellReuseIdentifier: TableViewCell.identifire)
tableView.reloadData()
}
}
}
extension ViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ImageURLModel.SearchKeysectionTitle
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
}
extension ViewController:UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.frame.size.height / 4
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifire, for: indexPath) as! TableViewCell
return cell
}
}
終わり
ご指摘、ご質問などありましたら、コメントまでお願い致します。