[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 ...
随机推荐
- 洛谷——P2035 iCow
P2035 iCow 题目描述 被无止境的农活压榨得筋疲力尽后,Farmer John打算用他在MP3播放器市场新买的iCow来听些音乐,放松一下.FJ的iCow里存了N(1 <= N < ...
- logstash日志写到es,按照时间来进行切割,生成索引配置
配置如下: es创建索引使用: logstash-chat-proxy-nginx-access-* logstash-chat-proxy-nginx-error-*
- webpack2 热加载js 文件
如果只要普通的热加载 只要如下配置就好了 package.json { "devDependencies": { "webpack": "^2.6.1 ...
- luogu P3375 【模板】KMP字符串匹配
题目描述 如题,给出两个字符串s1和s2,其中s2为s1的子串,求出s2在s1中所有出现的位置. 为了减少骗分的情况,接下来还要输出子串的前缀数组next.如果你不知道这是什么意思也不要问,去百度搜[ ...
- [BZOJ3224]普通平衡树(旋转treap,STL-vector)
3224: Tyvj 1728 普通平衡树 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 20328 Solved: 8979[Submit][St ...
- [BZOJ4861][BJOI2017]魔法咒语(AC自动机+矩阵优化DP)
4861: [Beijing2017]魔法咒语 Time Limit: 20 Sec Memory Limit: 256 MBSubmit: 217 Solved: 105[Submit][Sta ...
- Luogu P3362 Cool loves shaxian 生成函数
题意: 定义f(i)=∑ k∣i k^d(i≤n),给出q个询问,每个询问询问区间[l,r]的f(i)的和. n<=1e7 d<=1e18 q<=5e4 可以发现f(i)是个积性函数 ...
- 20162303实验四 Android程序设计
北京电子科技学院(BESTI) 实 验 报 告 课程:程序设计与数据结构 班级: 1623 姓名: 石亚鑫 学号:20162303 成绩: 2分 指导教师:娄嘉鹏 王志强 实验日期:5月26日 实验密 ...
- Java高级架构师(一)第39节:Nginx的Rewrite模块
- css3背景属性 background-size 对背景图进行缩小放大
background-size需要两个值,它的类型可以是像素(px).百分比(%)或是auto,还可以是cover和contain.第一个值为背景图的width,另外一个值用于指定背景图上的heigh ...