Good morning all,
I would like to write about table view's dynamic cell today.
When you make memo app or to-do app, you might want to sell the entire details of your memo on the memo list.
In this case, you could consider write the following codes;
import UIKit
// Custom Cell Class. I always recommend you to create the UITableViewCell class in a seperate file.
class CustomCell: UITableViewCell {
@IBOutlet weak var imageV: UIImageView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var desc: UILabel!
}
// Model
struct ExpandDataModel {
var description: String
var isExpand: Bool
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.desc.text = dataModels[indexPath.row].description
// The following codes are important. number of lines of zero will expand your UILabel to see the entire text.
if dataModels[indexPath.row].expand == true {
cell.desc.numberOfLines = 0
} else {
cell.desc.numberOfLines = 1
}
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dataModels[indexPath.row].expand = !dataModels[indexPath.row].expand
// Don't forget to reload data. Instead of using tableView.reloadData, I recommend you use reloadRows to optimize your app performance.
tableView.reloadRows(at: [indexPath], with: .automatic)
}
var dataModels = [ExpandDataModel]()
let textArray = [
"short text", "long text long text long text long text long text long text long text",
"short text", "long text long text long text long text long text long text long text",
"short text", "long text long text long text long text long text long text long text",
"short text", "long text long text long text long text long text long text long text",
"short text", "long text long text long text long text long text long text long text"
]
override func viewDidLoad() {
super.viewDidLoad()
for (_, value) in textArray.enumerated() {
dataModels.append(ExpandDataModel.init(description: value, expand: false))
}
// Do any additional setup after loading the view.
}
}
'iOS' 카테고리의 다른 글
iOS - UIImageView를 활용한 Animation 구현 (0) | 2020.07.17 |
---|---|
iOS - IBOutlet & IBAction (0) | 2020.07.16 |
Source Control with Xcode (0) | 2020.07.09 |
iOS - Defer문 (0) | 2020.05.07 |
iOS - Closure 최적화 (0) | 2020.04.30 |