其实,写这篇博客目的呢,就是给ios新手们提供一些帮助吧,少走些弯路。当然这都是小技巧了,大家仔细琢磨一下就会懂的。那言归正传,接下来,我就说下我学到的东西。
工具:Xcode 8.2.1版本
语言:Swift 3.0版本
目标:实现TableViewCell自定义高度
一个ViewController视图控制器文件,如下:
//
// ViewController.swift
// TableCustom
//
// Created by WangShuai on 17/3/21.
// Copyright © 2017年 cn.com.yisquare. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
let heightList = [50, 100, 150, 200, 250]
let list = ["打喷嚏是一想二骂三感冒", "打喷嚏是一想二骂三感冒,打喷嚏是一想二骂三感冒", "打喷嚏是一想二骂三感冒,打喷嚏是一想二骂三感冒,打喷嚏是一想二骂三感冒", "2015年7月26日 - swift UITableView cell自适应高度 2015-07-26 22:50 4050人阅读 评论(0) 收藏 举报 分类: ios(21) 作者同类文章X 版权声明:本文为博主原创文章,转载", "2016年9月6日 - 自定义了一个UITableViewCell用于展示一些新闻信息,类似于图里的样子,Cell里的内容不是固定的,有时候有图片有时候没有图片,标题和说明文字的长度也不确定。"]
let cellIdentifier: String = "cellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
print("测试TableView自定义高度")
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
tableView.separatorStyle = .none
tableView.register(Cell.self, forCellReuseIdentifier: "cellIdentifier")
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
self.view.addSubview(tableView)
self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0))
self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 20.0))
self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0))
self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: 0.0))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}