データ型Structの用意
- Tinderなどのプロフィールにあるデータをプロパティとして用意
- initで初期化
Girls.swift
import UIKit
struct Girl {
var name: String
var age: String
var type: String //職業など(ex. 学生, OLなど)
var distance: String
var image: UIImage
//初期化 //Girl(name: String, age: String, type: String, distance: String, image: UIImage)という感じでインスタンスにして使う
init(name: String, age: String, type: String, distance: String, image: UIImage) {
self.name = name
self.age = age
self.type = type
self.distance = distance
self.image = image
}
}
Viewに代入
配列を用意
var girlsData: [Girl] = [] //初期化してからの配列
private func setGirlsInfo() {
//データをセット
girlsData.append(Girl(name: "あや", age: "18", type: "学生", distance: "6 km", image: UIImage(named: "aya.png")!))
girlsData.append(Girl(name: "マイカ", age: "25", type: "OL", distance: "2 km", image: UIImage(named: "maika.png")!))
girlsData.append(Girl(name: "emi", age: "40", type: "パート", distance: "56 km", image: UIImage(named: "emi.png")!))
girlsData.append(Girl(name: "みゆ", age: "21", type: "大学生", distance: "10 km", image: UIImage(named: "miyu.png")!))
girlsData.append(Girl(name: "リンゴ", age: "29", type: "事務", distance: "16 km", image: UIImage(named: "ringo.png")!))
}
override func viewDidLoad() {
super.viewDidLoad()
setGirlsInfo()
}
Viewに配列の要素を代入
//girlsViewの要素にGirlのインスタンスの各要素を代入
private func setDataToGirlsView(girlsView: GirlsView, index: Int) {
girlsView.nameLabel.text = girlsData[index].name
girlsView.ageLabel.text = girlsData[index].age
girlsView.typeLabel.text = girlsData[index].type
girlsView.distanceLabel.text = girlsData[index].distance
girlsView.girlsImageView.image = girlsData[index].image
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Array(0..<girlsViewArray.count).forEach {
//省略
view.addSubview(girlsViewArray[$0]) //$0は0 ~ girlsViewArray-1
//省略
//girlsViewArrayの各要素にGirlのインスタンスを代入
setDataToGirlsView(girlsView: girlsViewArray[$0], index: $0)
//省略
}
}
完成図

完成したらgithubに後ほどリンク載せます