[Swift A] - 实战-豆瓣电台总结
最近在学Swift,也是刚刚开始。这里对自己最近所学做个简单的总结:视频和代码都在下面
http://pan.baidu.com/s/1sjHd5qX
1.String和NSString的不同
Swift的String类型是值类型。如果你创建了一个新的字符串值,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。 在不同的情况下,都会对已有字符串值创建新的副本,并对该新副本进行传递或赋值。 这和OC中的NSString不同,当您在OC创建了一个NSString实例,并将其传递给一个函数/方法,或者赋给一个变量,您永远都是传递或赋值同一个NSString实例的一个引用。 除非您特别要求其进行值拷贝,否则字符串不会进行赋值新副本操作。
2.异步获取数据
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response:NSURLResponse!, data:NSData!, error:NSError!)->Void in
var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
//why just miss an excalmatory mark, the code isn't compile
//self.delegate?.didRecieveResults(jsonResult)
})
3.UI焦点的易操作
在UI的界面种可以直接在View上点击鼠标右键,并拖入相应的Controller的代码中,且生成@IBOutlet和@IBAction。代码都不用手写了,很方便。

4.视图之间的跳转,传参,回跳
//页面跳转时,将数据传过去
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
var channelC:ChannelController = segue.destinationViewController as ChannelController
channelC.delegate = self// What TODO
channelC.channelData = self.channelData
}
//点击事件
func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
//what is do this
var rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
let channelId:AnyObject = rowData["channel_id"] as AnyObject
let channel:String = "channel=\(channelId)"
delegate?.onChangeChannel(channel)
self.dismissViewControllerAnimated(true, completion: nil)
}
5.MP3在线播放
//定义一个播放器
var audioPlayer:MPMoviePlayerController = MPMoviePlayerController() //设置音乐
func onSetAudio(url:String) {
timer?.invalidate()
timeLabel.text = "00:00" self.audioPlayer.stop()
self.audioPlayer.contentURL = NSURL(string:url)
self.audioPlayer.play()
timer = NSTimer.scheduledTimerWithTimeInterval(0.4 , target : self, selector : "onUpdate", userInfo: nil, repeats :true) playBtn.removeGestureRecognizer(tap)
logo.addGestureRecognizer(tap)
playBtn.hidden = true
}
6.TableView列表Item的出现动画
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
}
7.UI控件汇总
UIViewController
UITableViewDataSource
UITableViewDelegate
UIImageView
UILabel
UIButton
UIProgressView
UITableView
UITapGestureRecognizer
UIImage
MediaPlayer
8.最后把代码贴出来以供学习
import UIKit
import MediaPlayer
import QuartzCore class ViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate, HttpProtocol, ChannelProtocol{ @IBOutlet var logo: UIImageView
@IBOutlet var timeLabel: UILabel
@IBOutlet var buttonNext: UIButton
@IBOutlet var progressBar: UIProgressView
@IBOutlet var itemLayout: UITableView
//开始点击事件
@IBOutlet var tap: UITapGestureRecognizer = nil //这里必须为空,否则报错 @IBOutlet var playBtn: UIImageView //to cache the picture of songs
var imageCache = Dictionary<String, UIImage>() var eHttp:HttpController = HttpController()
//主界面
var tableData:NSArray = NSArray()
//频道列表
var channelData:NSArray = NSArray()
//定义一个播放器
var audioPlayer:MPMoviePlayerController = MPMoviePlayerController() var timer:NSTimer? @IBAction func onTap(sender: UITapGestureRecognizer) {
if sender.view == playBtn {
playBtn.hidden = true
audioPlayer.play()
playBtn.removeGestureRecognizer(tap)
logo.addGestureRecognizer(tap)
} else if sender.view == logo{
playBtn.hidden = false
audioPlayer.pause()
playBtn.addGestureRecognizer(tap)
logo.removeGestureRecognizer(tap)
}
} override func viewDidLoad() {
super.viewDidLoad()
//视图加载完之后,获取数据
eHttp.delegate = self
eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=0")
progressBar.progress = 0.0
logo.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
} //TODO
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
var channelC:ChannelController = segue.destinationViewController as ChannelController
channelC.delegate = self// What TODO
channelC.channelData = self.channelData
} func onChangeChannel(channelId:String) {
let url:String = "http://douban.fm/j/mine/playlist?\(channelId)"
eHttp.onSearch(url)
} func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
//列表展示
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "songs")
let rowData:NSDictionary = self.tableData[indexPath.row] as NSDictionary
cell.text = rowData["title"] as String
cell.detailTextLabel.text = rowData["artist"] as String
//默认图片
cell.image = UIImage(named:"detail.jpg")
//缩略图
let url = rowData["picture"] as String
let image = self.imageCache[url] as? UIImage
if !image?{// why do this
let imgURL:NSURL = NSURL(string:url)
let request:NSURLRequest = NSURLRequest(URL:imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
let img = UIImage(data:data)
cell.image = img
//缓存图片
self.imageCache[url] = img
})
} else {// if no this else, the item will be default image
cell.image = image
} return cell
} func didRecieveResults(results:NSDictionary) {
//println(results);
if(results["channels"]) {
self.channelData = results["channels"] as NSArray
//self.itemLayout.reloadData()
} else if(results["song"]) {
self.tableData = results["song"] as NSArray
self.itemLayout.reloadData() let firDict:NSDictionary = self.tableData[0] as NSDictionary
let audioUrl:String = firDict["url"] as String
onSetAudio(audioUrl)
let imgUrl:String = firDict["picture"] as String
onSetImage(imgUrl)
} } func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
let rowData:NSDictionary = self.tableData[indexPath.row] as NSDictionary
let audioUrl:String = rowData["url"] as String
onSetAudio(audioUrl)
let imgUrl:String = rowData["picture"] as String
onSetImage(imgUrl)
} //设置音乐
func onSetAudio(url:String) {
timer?.invalidate()
timeLabel.text = "00:00" self.audioPlayer.stop()
self.audioPlayer.contentURL = NSURL(string:url)
self.audioPlayer.play()
timer = NSTimer.scheduledTimerWithTimeInterval(0.4 , target : self, selector : "onUpdate", userInfo: nil, repeats :true) playBtn.removeGestureRecognizer(tap)
logo.addGestureRecognizer(tap)
playBtn.hidden = true
} func onUpdate() {
let c = audioPlayer.currentPlaybackTime
if c > 0.0 {
let t = audioPlayer.duration
let p:CFloat=CFloat(c/t) progressBar.setProgress(p, animated: true) let allSecond:Int = Int(c)
let s:Int = allSecond%60
let m:Int = Int(allSecond/60)
var time:String = ""
if(m < 10) {
time = "0\(m)"
} else {
time = "\(m)"
}
if(s < 10) {
time += ":0\(s)"
} else {
time += ":\(s)"
}
timeLabel.text = time }
} //设置图片
func onSetImage(url:String) {
let image = self.imageCache[url] as? UIImage
if !image?{// why do this
let imgURL:NSURL = NSURL(string:url)
let request:NSURLRequest = NSURLRequest(URL:imgURL)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
let img = UIImage(data:data)
self.logo.image = img
//缓存图片
self.imageCache[url] = img
})
} else {// if no this else, the item will be default image
self.logo.image = image
} } }
import UIKit
protocol HttpProtocol {
func didRecieveResults(results:NSDictionary)
}
class HttpController : NSObject {
var delegate:HttpProtocol?
func onSearch(url:String) {
var nsUrl:NSURL = NSURL(string:url)
var request:NSURLRequest = NSURLRequest(URL:nsUrl)
//1.Closure Expression Syntax
//2.异步获取数据
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response:NSURLResponse!, data:NSData!, error:NSError!)->Void in
var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
//why just miss an excalmatory mark, the code isn't compile
//self.delegate?.didRecieveResults(jsonResult)
})
}
}
import UIKit
import QuartzCore protocol ChannelProtocol {
func onChangeChannel(channelId:String)// why is String, is not NSString
} class ChannelController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var listLayout: UITableView var channelData:NSArray = NSArray()
var delegate:ChannelProtocol? override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 10
} func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
} func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "channel")
let rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
cell.text = rowData["name"] as String
return cell
} func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
//what is do this
var rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
let channelId:AnyObject = rowData["channel_id"] as AnyObject
let channel:String = "channel=\(channelId)"
delegate?.onChangeChannel(channel)
self.dismissViewControllerAnimated(true, completion: nil)
} }
[Swift A] - 实战-豆瓣电台总结的更多相关文章
- Swift实战-豆瓣电台(九)简单手势控制暂停播放(全文完)
Swift实战-豆瓣电台(九)简单手势控制暂停播放 全屏清晰观看地址:http://www.tudou.com/programs/view/tANnovvxR8U/ 这节我们主要讲UITapGestu ...
- Swift实战-豆瓣电台(八)播放进度与时间
视频观看地址:http://www.tudou.com/programs/view/4mEtz8S72k0/?resourceId=399000367_06_02_99 这节主要内容是NSTimer, ...
- Swift实战-豆瓣电台(七)显示动画
youku观看地址http://v.youku.com/v_show/id_XNzMxODQzNDIw.html 这是一个很酷的动画效果.特别是数据多的时候 知识点 在单元格(Cell)显示方法中设置 ...
- Swift实战-豆瓣电台(六)视图跳转,传参及回跳
youku观看地址:http://v.youku.com/v_show/id_XNzMxMzQ3MDcy.html 要点 在ChannelController里面声明一个代理 这个代理遵循我们自定义的 ...
- Swift实战-豆瓣电台(五)播放音乐
观看地址 http://v.youku.com/v_show/id_XNzMwODM0MzI0.html 在这节里面,我们简单学习了一下MediaPlayer的使用 引入媒体框架 import Med ...
- Swift实战-豆瓣电台(四)歌曲列表的展现
观看地址 http://v.youku.com/v_show/id_XNzMwNDE0OTA4.html 这节的主要内容是如何利用cell展现获取到的数据. 首先申明两个数组来储存我们获取到的数据 v ...
- Swift实战-豆瓣电台(三)获取网络数据
观看地址:http://v.youku.com/v_show/id_XNzMwMzQxMzky.html 这节内容,我们先说了怎么将storyboard中的组件在类中进行绑定.然后写了一个类用来获取网 ...
- Swift实战-豆瓣电台(一)准备
一 准备 我们现在看看我们要做一个什么样的东西 观看地址:http://v.youku.com/v_show/id_XNzI4ODY2Mjky.html 布局 通过上面这张图我们可以看出整个demo有 ...
- Swift实战-豆瓣电台(二)界面布局
观看地址 http://v.youku.com/v_show/id_XNzMwMDg4NzAw.html 这节的内容主要是storyboard的操作. 有以下几个知识点 1 TableView的Dat ...
随机推荐
- CSS页面排版的一点笔记
CSS页面排版 字体族 字体族的值是一个字体备选列表,多个字体使用英文逗号隔开,字体名称如果有空格则需要引号. font-family: "Georgia Pro", " ...
- UGUI的优点新UI系统三效率高效果好
UGUI的优点新UI系统三效率高效果好 通过对批处理(batching).纹理图集(texture atlasing)和新的canvas组件的支持,新UI系统提供了一个经过优化的解决方案,使得开发者添 ...
- [Atcoder Regular Contest 061] Tutorial
Link: ARC061 传送门 C: 暴力$dfs$就好了 #include <bits/stdc++.h> using namespace std; typedef long long ...
- 【最大流】BZOJ1305-[CQOI2009]dance跳舞
[题目大意] 一次舞会有n个男孩和n个女孩.每首曲子开始时,所有男孩和女孩恰好配成n对跳交谊舞.每个男孩都不会和同一个女孩跳两首(或更多)舞曲.有一些男孩女孩相互喜欢,而其他相互不喜欢(不会“单向喜欢 ...
- [AGC019E]Shuffle and Swap
[AGC019E]Shuffle and Swap 题目大意: 给出两个长度为\(n(n\le10000)\)的\(01\)串\(A_{1\sim n}\)和\(B_{1\sim n}\).两个串均有 ...
- [PKUSC2018]最大前缀和
[PKUSC2018]最大前缀和 题目大意: 有\(n(n\le20)\)个数\(A_i(|A_i|\le10^9)\).求这\(n\)个数在随机打乱后最大前缀和的期望值与\(n!\)的积在模\(99 ...
- PHP“Cannot use object of type stdClass as array”
php再调用json_decode从字符串对象生成json对象时,如果使用[]操作符取数据,会得到下面的错误 错误:Cannot use object of type stdClass as arra ...
- 几本推荐的Java书
一.<深入理解Java虚拟机:JVM高级特性与最佳实践> 如果你不满足于做一个只会写if…else…的Java程序员,而是希望更进一步,我随便举几个例子吧: 1.了解Java代码的底层运行 ...
- rocketmq,zookeeper,redis分别持久化的方式
1.rocketmq持久化: RocketMQ 的所有消息都是持久化的, 先写入系统 PAGECACHE, 然后刷盘, 可以保证内存与磁盘都有一份数据,访问时,直接从内存读取. RocketMQ 的所 ...
- 【Rocket MQ】RocketMQ 在windows7 64位安装使用 +RocketMQ管理界面的安装
参考地址:https://blog.csdn.net/yucaifu1989/article/details/80960018 参考地址:https://blog.csdn.net/u01204090 ...