http://yuu.1000quu.com/use_a_custom_cell_in_swift
この記事を参考にしてこのような感じのカスタムセルを作りました
swift
1ViewController.swift 2import UIKit 3 4class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 5 6 @IBOutlet weak var tableview: UITableView! 7 8 let imageNames: [String] = ["https://pbs.twimg.com/profile_images/853593889633992706/gszvGP-0.jpg"] 9 let testlabel: [String] = ["testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"] 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 self.tableview.estimatedRowHeight = 100.0 13 self.tableview.rowHeight = UITableViewAutomaticDimension 14 } 15 16 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 17 return imageNames.count 18 } 19 20 /// セルに値を設定するデータソースメソッド(必須) 21 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 22 // セルを取得 23 let cell = tableView.dequeueReusableCell(withIdentifier: "cells") as! CustomTableViewCell 24 25 // セルに値を設定 26 cell.setCell(IconImage: imageNames[indexPath.row], testlabel: testlabel[indexPath.row]) 27 28 return cell 29 } 30}
swift
1CustomTableViewCell.swift 2import UIKit 3 4class CustomTableViewCell: UITableViewCell { 5 @IBOutlet weak var cellimg: UIImageView! 6 @IBOutlet weak var celllabel: UILabel! 7 8 override func awakeFromNib() { 9 super.awakeFromNib() 10 } 11 12 override func setSelected(_ selected: Bool, animated: Bool) { 13 super.setSelected(selected, animated: animated) 14 } 15 func setCell(IconImage: String, testlabel: String) { 16 let url = NSURL(string: IconImage) 17 let req = NSURLRequest(url:url! as URL) 18 19 NSURLConnection.sendAsynchronousRequest(req as URLRequest, queue:OperationQueue.main){(res, data, err) in 20 21 let image = UIImage(data:data!) 22 self.cellimg.image = image 23 self.celllabel.text = testlabel 24 } 25 cellimg.image = UIImage(named: IconImage) 26 } 27}
セルに表示するテキストは長い文章のため、セルの高さを自動調節するために
ViewController.swiftに
self.tableview.estimatedRowHeight = 100.0
self.tableview.rowHeight = UITableViewAutomaticDimension
を追加し、
その文章の表示に使われるLabelにAutolayoutを設定し、Linesも0に設定しました
しかし、ビルドして確認してみるとこうなってしまいます。
カスタムセルで長い文章を複数行表示し、セルの高さを自動調節するにはどのようにすれば良いでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/04/28 05:49