[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 ...
随机推荐
- 洛谷—— P1598 垂直柱状图
P1598 垂直柱状图 题目描述 写一个程序从输入文件中去读取四行大写字母(全都是大写的,每行不超过72个字符),然后用柱状图输出每个字符在输入文件中出现的次数.严格地按照输出样例来安排你的输出格式. ...
- 04、Unity 5--全局光照技术
本文整理自Unity全球官方网站,原文:UNITY 5 - LIGHTING AND RENDERING 简介全局光照,简称GI,是一个用来模拟光的互动和反弹等复杂行为的算法,要精确的仿真全局光照非常 ...
- 写的模块和方法 wap 和 pc
createjs 画了一个曲线功能 rem 的适配方式 $.fn.stop 方法, zepto 没有的, 对于 2d的旋转 变形 还有 移动都可以停下来, 做动画的属性存储, getComputedS ...
- 初见Python<4>:字典
序列是python中的一种数据结构,映射是另一种.映射(mapping)通过名字来引用值.python内建的唯一一种映射结构是字典.字典中的值没有特殊的顺序,但都存储在一个特定的键中.键可以是数字.字 ...
- 【推导】【构造】XVII Open Cup named after E.V. Pankratiev Stage 14, Grand Prix of Tatarstan, Sunday, April 2, 2017 Problem E. Space Tourists
给你n,K,问你要选出最少几个长度为2的K进制数,才能让所有的n位K进制数删除n-2个元素后,所剩余的长度为2的子序列至少有一个是你所选定的. 如果n>K,那么根据抽屉原理,对于所有n位K进制数 ...
- JDK源码学习笔记——Iterable/Iterator实现原理
Collection接口继承java.lang.Iterable接口,集合类重写了iterator()方法 public interface Iterable<T> { Iterator& ...
- 微信小程序-微信自动退款(Java后台)
微信小程序-微信自动退款 1.首先分享 微信自动退款接口: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4 微信付款 代码案例 ...
- .Net 2014 Connect() 相关文章合集
微软在11月中旬的Connect()研讨会中公布了一系列 2015年的发展规划,今天在MSDN Blog上看到了一篇比较全的相关文章合集,这里转录一下,感兴趣的朋友可以看看. Announcement ...
- Linux PHP 编译参数详解(二)
对于喜欢玩开源软件的童鞋么,都喜欢自己编译安装程序,本文说明下如何编译安装php的详细参数. 示例: ./configure \ --prefix=/usr/local/php --with-zlib ...
- Do waiting or suspended tasks tie up a worker thread?
https://blogs.msdn.microsoft.com/askjay/2012/07/29/do-waiting-or-suspended-tasks-tie-up-a-worker-t ...