Beginning iOS 8 Programming with Swift-TableView

UITableView控件使用

使用UITableView,在控件库中,拖拽一个Table View到ViewController中,在Controller的后台代码中需要继承UITableViewDelegate和UITableViewDataSource的协议。
重写方法
tableView(_:numberOfRowsInSection)
此方法是UITableViewDataSource协议的方法,返回tableView加载的行数。
实例代码
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
//返回table中每个节点行数,在tableView中还可以使用节,就是组。后续介绍组的用法
return restaurantNames.count
}
tableView(_:cellForRowAtIndexPath)
此方法是UITableViewDatSource协议的方法,该方法中实现如何加载TableView中的数据。
实例代码
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell {
//这里是的Cell是在Storyboard中设置的tableViewCell的Identifier
let cellIdentifier = "Cell"
//这就是获取单元格
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath:
indexPath) as UITableViewCell
// Configure the cell...
cell.textLabel.text = restaurantNames[indexPath.row]
return cell
}
dequeueReusableCellWithIdentifier:从queue中取回一个名称是[identifier]的可用的单元格。这里为什么是从列队中取:看如下解释:

设置dataSource和delegate

两种方式设置tableView的dataSource和delegate

  1. 在Storyboard中右键选择tableView


将dataSource和delegate拖动到当前的ViewController上

  1. 在Controller的代码中,链接tableView

@IBOutlet var tableView: UITableView!
然后再viewDidLoad的方法中设置tableView的dataSource和delegate
tableView.dataSource = self
tableView.delegate = self

设置单元格的缩略图

在tableView(_:cellForRowAtIndexpath)的方法中
cell.imageView.image = UIImage(name:"imagename")

隐藏状态栏

override func prefersStatusBarHidden() -> Bool {
return true
}

自定义单元格

修改Custom属性

在storyboard中选择tableViewCell,在属性索引器中,将Style的属性变更为Custom

修改tableView行高

修改单元格行高

自定义单元格样式

在控件库中,可以拖拽控件到单元格中拜访出自己想要的格式

为自定义单元格创建类文件

在工程中添加新文件(command + N),选择Cocoa Touch Class,在SubClass of中选择UITableViewCell,不需要xib文件。
在类文件中定义控件
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var thumbnailImageView: UIImageView!

关联类文件和控件定义

设置tableViewCell的class为新建的class

设置控件关联

关联后结果

修改获取单元格的方法

在tableView(_:cellForRowAtIndexpath)的方法中,把原来的获取单元格的方法修改
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath:
indexPath) as UITableViewCell
修改后
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath:
indexPath) as CustomTableViewCell
CustomTableViewCell就是我们新定义的类
设置单元格
cell.nameLabel.text = restaurantNames[indexPath.row]
cell.thumbnailImageView.image = UIImage(named: restaurantImages[indexPath.row])

如何设置图片圆角

代码实现:
cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width / 2
cell.thumbnailImageView.clipsToBounds = true
clipsToBounds是一个属性开关,只有打开,圆角设置才有效
设置实现:
选择ImageView控件,做如下设置

在User Defined Runtime Attributes中添加key 和 value。 这时不需要设置开关。
同样,我们可以在这里修改backgroundColor,Fond…

单元格选择和UIAlertController

在UITableViewDelegate的协议中,有两个方法
tableView(_:willSelectRowAtIndexpath) 选择前
tableView(_:didSelectRowAtIndexpath) 选择后

设置单元格选中

let cell = tableView.cellForRowAtIndexPath(indexPath)
通过indexPath来获取单元格的时候会产生一个Bug,前面我们有讲过,Cell的加载是通过queue中获取,受queue的印象,在获取cell的时候,会有错位的Bug,解决这个问题的方法是通过控制数据源来解决。
通过设置cell的accessoryType来设置cell的选中状态
cell.accessoryType = UITableViewCellAccessoryType.Checkmark

UIAlertController的使用

实例代码我们写在tableView(_:didSelectRowAtIndexpath)的方法中
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:
NSIndexPath) {
// Create an option menu as an action sheet
let optionMenu = UIAlertController(title: nil, message: "What do you want to do?",
preferredStyle: .ActionSheet)
// Add actions to the menu
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
optionMenu.addAction(cancelAction)
// Display the menu
self.presentViewController(optionMenu, animated: true, completion: nil)
}
UIAlertControllerStyle有两种,
.Alert
.ActionSheet

1、使用AlertController首先是要创建UIAlertController对象
let optionMenu = UIAlertController(title: nil, message: "What do you want to do?",
preferredStyle: .ActionSheet)
2、然后创建UIAlertAction
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
3、把action添加到Controller中,如果AlertControllerStyole是.ActionSheet,那么在AlertController中可以添加多个Action
optionMenu.addAction(cancelAction)
4、呈现AlertController
// Display the menu
self.presentViewController(optionMenu, animated: true, completion: nil)
在创建action中,有关handler,这里是个委托,可以用闭包实现,也可以做个函数传递函数名称,就是在action点击后触发的委托
let isVisitedAction = UIAlertAction(title: "I‘ve beenhere", style: .Default, handler: {
(action:UIAlertAction!) -> Void in
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.accessoryType = .Checkmark
self.restaurantIsVisited[indexPath.row] = true
})
简化闭包写法
let isVisitedAction = UIAlertAction(title: "I‘ve beenhere", style: .Default) {
//$0表示第一个参数,这里关闭闭包用法可以参考语法笔记
let sender = $0
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.accessoryType = .Checkmark
self.restaurantIsVisited[indexPath.row] = true
}

UIAlertView

UIAlertView类似UIAlertController中的Action,使用相对简单
let alertView = UIAlertView(title:"", message:"", delegate:nil, cancelButtonTitle:"")
alertView.show()

TableRow的删除

在UITableViewDataSource的协议中有个方法
tableView(_:commitEditingStyle:forRowAtIndexPath
在ViewController的类中重写该方法,不做任何实现可以看到如下效果
override func tableView(tableView: UITableView, 
commitEditingStyle editingStyle:UITableViewCellEditingStyle, 
forRowAtIndexPath indexPath: NSIndexPath) {
}

当点击删除按钮,如果要做相关操作,可以在上述方法中实现
实例代码:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle:
UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
self.restaurantNames.removeAtIndex(indexPath.row)
self.restaurantLocations.removeAtIndex(indexPath.row)
self.restaurantTypes.removeAtIndex(indexPath.row)
self.restaurantIsVisited.removeAtIndex(indexPath.row)
self.restaurantImages.removeAtIndex(indexPath.row)
//删除row
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
}
//重新加载tableView
self.tableView.reloadData() 
}

添加RowAction

在IOS 8 SDK中有个新成员UITableViewRowAction,利用这个新成员,我们可以在Row上面有更多的操作

  1. 重写UITableViewDataSource的一个方法tableView(_:editActionsForRowAtIndexPath)
  2. 创建UITableViewRowAction

var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title:
"Share", handler:nil)

  1. 实现Action后的委托
  2. 返回RowAction

实例代码:
override func tableView(tableView: UITableView, 
editActionsForRowAtIndexPath indexPath:
NSIndexPath) -> [AnyObject] {
var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title:
"Share", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
let shareMenu = UIAlertController(title: nil, message: "Share using",
preferredStyle: .ActionSheet) 
let twitterAction = UIAlertAction(title: "Twitter", style:
UIAlertActionStyle.Default, handler: nil)
let facebookAction = UIAlertAction(title: "Facebook", style:
UIAlertActionStyle.Default, handler: nil)
let emailAction = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default,
handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel,
handler: nil)
shareMenu.addAction(twitterAction)
shareMenu.addAction(facebookAction)
shareMenu.addAction(emailAction)
shareMenu.addAction(cancelAction)
self.presentViewController(shareMenu, animated: true, completion: nil)
}
)
var deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default,
title: "Delete",handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
// Delete the row from the data source
self.restaurantNames.removeAtIndex(indexPath.row)
self.restaurantLocations.removeAtIndex(indexPath.row)
self.restaurantTypes.removeAtIndex(indexPath.row)
self.restaurantIsVisited.removeAtIndex(indexPath.row)
self.restaurantImages.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
)
return [deleteAction, shareAction]
}

时间: 2024-08-03 21:36:48

Beginning iOS 8 Programming with Swift-TableView的相关文章

[iOS翻译]《The Swift Programming Language》系列:Welcome to Swift-01

本文转载至:http://www.cnblogs.com/yangfaxian/p/3765081.html 全书目录: 一.Welcome to Swift 二.Language Guide 三.Language Reference /* 译者的废话: 几个小时前熬夜看了WWDC,各种激动,今年很有料啊!当看到Swift出来的时候,瞬间傻眼,又要学习新语言了.这篇文章来自苹果官方的<The Swift Programming Language>一书,500页左右,在苹果官网有下载.Swift

学习 About iOS App Programming 第三天

-------State Preservation and Restoration 即使我们的app能支持后台运行,但它也不能一直在后台运行,有一些情况,系统也许会需要终止app,为了释放内存给在前台运行的app.但是用户不关心app是不是被关闭,用户只知道这个app应用就是这个地方暂停了,当再次起来时应该就在上一次退出的地方.这样用户能继续进行他上次没有完成的任务.因此UIKit实现了这种功能. UIKit的状态保存系统提供了一个简单同时比较精准的基础技术对于保存和恢复app viewcont

iOS 从Objective-C到Swift

前言: 博主功力有限, 也是在学习的过程中, 之前写了几篇在iOS开发中使用Swift进行开发偏向于UI方向的文章, 明显地感觉到OC与Swift的之间的一些区别与联系, 并且还有一些值得注意的地方, 希望看到这篇文章的小伙伴更快地上手Swift. , 最近自己的状态也是很糟糕, 更糟糕的是感冒了(囧~). 有什么错误请评论指出, 谢谢. 一 属性 OC中 我们最常用的property // 常常会这样写 @property (nonatomic, copy) NSString *name; S

iOS Dev (63) 如何在 TableView 滚动时收起键盘?

iOS Dev (63) 如何在 TableView 滚动时收起键盘? 作者:阿锐 地址:http://blog.csdn.net/prevention - - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [_inputTextView resignFirstResponder]; } - 转载请注明来自:http://blog.csdn.net/prevention iOS Dev (63) 如何在 TableView 滚动时收

Professional iOS Network Programming Connecting the Enterprise to the iPhone and iPad

Book Description Learn to develop iPhone and iPad applications for networked enterprise environments The iPhone and iPad have made a powerful impact on the business world. Developers creating iOS apps for the enterprise face unique challenges involvi

Swift技术之如何在iOS 8下使用Swift设计一个自定义的输入法 (主要是NSLayoutConstraint 的使用)

当前位置: > Swift新手入门 > Swift技术之如何在iOS 8下使用Swift设计一个自定义的输入法 时间:2014-09-10 16:49来源:未知 作者:啊成 举报 点击:562次 我会复习一下有关键盘扩展的内容,然后通过使用iOS 8中的新应用扩展API的设计一个摩斯码的输入法.完成这个教程大约需要花费20分钟.完整代码 概览 通过使用自定义输入法替换系统输入法,用户可以实现一些特别的功能.例如一个特别新颖的输入方式,或输入iOS原生并不支持的语言.自定义输入法的基本功能很简单

Swift TableView

代码来源  cocoachina推荐源码  26日 上面这些是一些基本的设置,然后提前补充几个知识点! 类后面的!作用是强制类型转换 NSCoder是一个抽象类,是字节流的抽象类,我们可以把数据写入一个coder也可以从coder中读出数据! as也可以类型为类型转换 Swift中sort函数有两种用法,在编译器中输入sort查看帮助文档有相信解释! 建议观看Swift language 函数章节 import UIKit class ViewController: UITableViewCon

翻译Beginning iOS 7 Development中文版

不会iOS开发好像真的说不过去,来本中文版的Beginning iOS 7 Development吧. 看了Beginning iOS 7 Development这本书,感觉蛮不错的.全英文的,没有中文版. 看到有很多人求中文版的帖子,想抽个时间翻译一下,不知道需求大不大. 如果有人看到我的这篇文章,并且有中文版需求,那么请发个评论. 英文版高清下载地址:http://download.csdn.net/detail/fylz1125/7549069 如果评论达到50条的话,我就翻译这本书,在我

[iOS翻译]《iOS 7 Programming Cookbook》:iOS文件与文件夹管理(上)

简介: iOS基于OS X,而OSX本身基于Unix操作系统.在iOS里面,操作系统的完全路径结构是不可见的,因为每个APP的数据都存储自身的沙盒里面.沙盒环境实际上听起来像这样:一个只允许当前APP访问的文件夹目录.每个APP都有自身的沙盒文件夹,并且沙盒文件夹下的子文件夹只有当前APP能够访问. 当一个iOS APP在设备上安装后,系统为其创建的文件夹结构如下: XXX.app 即Main Bundle Documents/ 存储用户创建的内容 Library/ 存储缓存文件.偏好设置等等