简介:
1.纯代码创建tableview
2.自定义tableViewCell
3.把搜索栏添加到表头
4.动态添加删除tableViewCell
另,我是把表格的数据保存到plist文件中的。保存、修改和删除数据的代码没有贴出来。
一、MainViewController文件
import UIKit
class MainViewController: UIViewController {
//保存表格数据的数组
var list: NSArray!
let dao = DAO.sharedInstance //数据源
var selectedDict: Dictionary<String,String>? = nil //保存选中Cell的数据进数组
//定义搜索栏
var mySearchController: UISearchController!
//搜索栏过滤后的数组
var listFilter = [Dictionary<String, Any>]()
override func viewDidLoad() {
super.viewDidLoad()
//设置搜索栏
setSearchBar()
//初始化表视图
initTable()
//注册并接收添加tableCell的通知
registerNotifigation()
}
deinit
{
//注销通知
NotificationCenter.default.removeObserver(self)
self.mySearchController.view.removeFromSuperview()
}
///初始化表视图
func initTable() {
//注册TableViewCell
table.register(CustomTableViewCell.self,forCellReuseIdentifier: "CellIdentifier")
//设置表视图委托对象为self
self.table.delegate = self
//设置表视图数据对象为self
self.table.dataSource = self
//去除表格尾部多余的空行
table.tableFooterView = UIView(frame: CGRect.zero)
//添加表格视图
viewForTable.addSubview(table)
//设置表视图背景
// let image = UIImage(named: "table_background")
// let imageView = UIImageView(image: image)
// self.table.backgroundView = imageView
//设置table的分割线
table.separatorStyle = .singleLine
//获取表视图显示数据
list = dao.readDeviceData(key: key_DeciveTableDisplay) as NSArray!
}
func setSearchBar() {
//配置搜索控制器
self.mySearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchBar.delegate = self //搜索栏不是实时搜索的代理
controller.hidesNavigationBarDuringPresentation = false
//true则在搜索时背景有一层透明灰
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.searchBarStyle = .default
//controller.loadViewIfNeeded()
//true则保证在UISearchController在激活状态下用户push到下一个view controller之后,search bar不会仍留在界面上。
controller.definesPresentationContext = true
//将搜索栏放到表视图的表头中
controller.searchBar.sizeToFit()
self.table.tableHeaderView = controller.searchBar
return controller
})()
}
///注册并接收添加设备的通知
private func registerNotifigation() {
NotificationCenter.default.addObserver(forName: addCellNotification, object: nil, queue: nil) { (notification) in
self.list = self.dao.readData(key: key_TableDisplay) as NSArray
//刷新表格数据和界面
self.table.reloadData()
self.viewForTable.setNeedsLayout()
}
}
// MARK: - 懒加载控件
// TableView
lazy var table: UITableView = {
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
let table = UITableView(frame: CGRect(x: 0, y: 0, width: screenWidth , height: screenHeight ))
return table
}()
}
二、mainVCExtention_TableView.swift文件
import UIKit
extension MainViewController: UITableViewDelegate ,UITableViewDataSource {
// MARK: - UITableViewDelegate 协议方法 //
///设置TableViewCell的高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
///tableView点击事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("clicked at \(indexPath.row)")
self.selectedDict = self.list[indexPath.row] as? Dictionary<String,String>
}
///tableView删除事件
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
//删除plist文件里指定的数据
self.dao.deleteData(key: key_TableDisplay, index: indexPath.row)
//获取表视图显示数据
self.listDevice = dao.readData(key: key_TableDisplay) as NSArray
//刷新表格
self.table.reloadData()
self.viewForTable.setNeedsLayout()
}
}
// MARK: - UITableViewDataSource 协议方法///
///返回表格中分区的数量
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
///设置UITableViewCell数量
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.list.count
}
///为UITableViewCell提供数据,必须实现的方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier = "CellIdentifier"
var cell:CustomTableViewCell! = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) as? CustomTableViewCell
if cell == nil
{
cell = CustomTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
}
let row = indexPath.row
let rowDict = self.list[row] as! Dictionary<String, Any>
cell.label_Name.text = rowDict["name"] as? String
cell.label_subTitle.text = rowDict["sub"] as? String
//获取图片名字
let imageFile = rowDict["image"] as? String
let imagePath = String(format: "%@.png", imageFile!)
//获取图片
cell.imageView.image = UIImage(named: imagePath)
//设置cell样式
cell.accessoryType = .none
cell.tag = indexPath.row
return cell
}
// 指定分区的头部
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
let header = ["分区1","分区2"] as [String]
return header[section]
}
// 指定分区的尾部
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?
{
return "有\(list.count)单元格"
}
}
三、CustomTableViewCell.swift文件
import UIKit
class CustomTableViewCell: UITableViewCell {
var label_Name: UILabel!
var label_subTitle: UILabel!
var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
if !self.isEqual(nil)
{
///1. 添加iamgeView
self.imageView = UIImageView()
self.contentView.addSubview(self.imageView)
setUpImageView()
///2.1 添加标签Name
self.label_Name = UILabel()
self.label_Name.font = UIFont.italicSystemFont(ofSize: 26)
self.addSubview(self.label_Name)
setUpLabelName()
///2.2 添加标签subTitle
self.label_subTitle = UILabel()
self.label_subTitle.font = UIFont.italicSystemFont(ofSize: 16)
self.addSubview(self.label_ipAdress)
setUpLabelSubTitle()
///3. cell的背景颜色
// self.backgroundColor = lightBlueColor
// ///4. 设置cell的图层为圆角边框
// self.layer.masksToBounds = true
// self.layer.cornerRadius = 30
}
}
private func setUpImageView() {
//系统默认会给autoresizing 约束,要关闭autoresizing才能让自定义的约束生效,否则程序崩溃
self.imageView_Device.translatesAutoresizingMaskIntoConstraints = false
//添加约束:"哪个控件" 的 “什么属性“ "等于/大于/小于" “另一个控件” 的 “什么属性” 乘以 "多少" 加上 "多少"
let imageConstraint_bottom = NSLayoutConstraint(item: self.imageView_Device, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: self, attribute: .bottom, multiplier: 1, constant: 10)
let imageConstraint_top = NSLayoutConstraint(item: self.imageView_Device, attribute: .top, relatedBy: .lessThanOrEqual, toItem: self, attribute: .top, multiplier: 1, constant: 10)
let imageConstraint_left = NSLayoutConstraint(item: self.imageView_Device, attribute: .left, relatedBy: .lessThanOrEqual, toItem: self, attribute: .left, multiplier: 1, constant: 100)
NSLayoutConstraint.activate([imageConstraint_bottom,imageConstraint_top,imageConstraint_left])
}
private func setUpLabelName() {
self.label_Name.translatesAutoresizingMaskIntoConstraints = false
let labelNameConstraint_bottom = NSLayoutConstraint(item: self.label_Name, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: self, attribute: .bottom, multiplier: 1, constant: 10)
let labelNameConstraint_top = NSLayoutConstraint(item: self.label_Name, attribute: .top, relatedBy: .lessThanOrEqual, toItem: self, attribute: .top, multiplier: 1, constant: 10)
let labelDeviceNameConstraint_left = NSLayoutConstraint(item: self.label_Name, attribute: .left, relatedBy: .lessThanOrEqual, toItem: self, attribute: .left, multiplier: 1, constant: 180)
NSLayoutConstraint.activate([labelDeviceNameConstraint_bottom,labelNameConstraint_top,labelNameConstraint_left])
}
private func setUpLabelSubtitle() {
self.label_subtitle.translatesAutoresizingMaskIntoConstraints = false
let labelSubtitleConstraint_bottom = NSLayoutConstraint(item: self.label_label_subTitle, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: self, attribute: .bottom, multiplier: 1, constant: 3)
let labelsubtitleConstraint_top = NSLayoutConstraint(item: self.label_label_subTitle, attribute: .top, relatedBy: .lessThanOrEqual, toItem: self, attribute: .top, multiplier: 1, constant: 50)
let labelsubtitleConstraint_left = NSLayoutConstraint(item: self.label_label_subTitle, attribute: .left, relatedBy: .lessThanOrEqual, toItem: self, attribute: .left, multiplier: 1, constant: 180)
NSLayoutConstraint.activate([labelsubtitleConstraint_bottom,labelsubtitleConstraint_top,labelsubtitleConstraint_left])
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
if selected
{
//改变cell的视图
}
}
四、mainVCExtension_SearchBar.swift文件
import UIKit
extension MainViewController: UISearchBarDelegate {
// called when keyboard search button pressed
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//var listDeciceName = [String]()
//获取表视图显示数据
let list = self.dao.readData(key: key_DeciveTableDisplay) as! Array<Dictionary<String, Any>>
for item in list
{
let temp = item["name"] as! String
if temp.contains(searchBar.text!)//如果设备名包含查找的字符
{
self.listDeviceFilter.append(item)
}
}
self.listDevice = self.listDeviceFilter as NSArray!
table.reloadData()
listDeviceFilter.removeAll()
}
// called when cancel button pressed
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.list = self.dao.readData(key: key_DeciveTableDisplay) as NSArray!
self.table.reloadData()
}
// return NO to not become first responder
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
}