最近Swiftを書き始めました.カスタムクラスとか作って見たらちょっとは深められるんじゃねってことで,巷で話題の(?)CustomCellを作ってみました.結果的にはSwiftというよりAuto Layoutでハマってしまいましたが...一応メモを残しておきます.
完成イメージ
Storyboard
まずStoryboardで概形を作ります.使うのはTableViewとTableViewCellですね.このTableViewCellのClassがデフォルトではUITableViewCellになっていますが,最終的にはCustomCellというカスタムクラスに変更します.さらに,Cellの中にUIImageViewとLabelを配置します.
Model
Cellの持つ情報のModelを作ります.
まずFile > new > File... から新しいSwift Fileを作成します.
それぞれのcellに渡すべき情報を持ってるだけのModelなんで中身はなんでもいいんですが,今回はNameとImageUrlをPropertyとしておきました.
import Foundation
class Friend : NSObject {
var name:NSString
var imageUrl:NSURL?
init(name: String, imageUrl: NSURL?){
self.name = name
self.imageUrl = imageUrl
}
}
CustomCell
CustomCellのクラスを作成します.新しいCocoa Classから,UITableViewCellのSubclassとしてCustomCellというクラスを作成しました.StoryboardからLabelとUIImageViewを結びつける必要があります.
import UIKit
class CustomCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var iconImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setCell(friend :Friend) {
self.name.text = friend.name
var err: NSError?
var imageData :NSData = NSData(contentsOfURL: friend.imageUrl!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)!
self.iconImage.image = UIImage(data:imageData)
}
}
ViewController
適当にダミーのデータをCustomCellに追加しました.StoryboardからTableViewを結びつける必要があります.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var tableView: UITableView!
var friends:[Friend] = [Friend]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.setupFriends()
self.tableView.delegate = self
self.tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupFriends() {
var f1 = Friend(name: "Ken", imageUrl: NSURL(string: "http://waka111.com/wp-content/uploads/2014/08/watanabek.jpg"))
var f2 = Friend(name: "Erika", imageUrl: NSURL(string: "http://dqaeric34olch.cloudfront.net/lists/57514/sawajirierika1.jpg/original?1416322567"))
var f3 = Friend(name: "Anna", imageUrl: NSURL(string: "http://cdnvideo.dolimg.com/cdn_assets/b5da8e4c0046a83b81dbd945719f6b354edd764b.jpg"))
friends.append(f1)
friends.append(f2)
friends.append(f3)
}
// functions needed to be implemented
// for table view
// セクション数
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// セクションの行数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as CustomCell
println(cell)
cell.setCell(friends[indexPath.row])
return cell
}
}
Auto Layout
Auto Layoutに関しては全然理解しておらず,画像のサイズ調整がよくわからなかったです...どこ見ればわかるんだろ...とりあえず,Intrinsic SizeをDefault(System Defined) ->PlaceholderにしてClip Subview(Overflow: hidden的な?)にチェックを入れたらいい感じになりました.
Source Code
GithubでSource Codeを公開しておきました.
https://github.com/seataK/CustomCellTutorial