最近在学Swift,也是刚刚开始。这里对自己最近所学做个简单的总结:视频和代码都在下面

http://pan.baidu.com/s/1sjHd5qX

1.String和NSString的不同

1 Swift的String类型是值类型。如果你创建了一个新的字符串值,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。
2
3 在不同的情况下,都会对已有字符串值创建新的副本,并对该新副本进行传递或赋值。
4
5 这和OC中的NSString不同,当您在OC创建了一个NSString实例,并将其传递给一个函数/方法,或者赋给一个变量,您永远都是传递或赋值同一个NSString实例的一个引用。
6
7 除非您特别要求其进行值拷贝,否则字符串不会进行赋值新副本操作。

2.异步获取数据

1  NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response:NSURLResponse!, data:NSData!, error:NSError!)->Void in
2             var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
3             //why just miss an excalmatory mark, the code isn't compile
4             //self.delegate?.didRecieveResults(jsonResult)
5         })

3.UI焦点的易操作

在UI的界面种可以直接在View上点击鼠标右键,并拖入相应的Controller的代码中,且生成@IBOutlet和@IBAction。代码都不用手写了,很方便。

4.视图之间的跳转,传参,回跳

1 //页面跳转时,将数据传过去
2     override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
3         var channelC:ChannelController = segue.destinationViewController as ChannelController
4         channelC.delegate = self// What TODO
5         channelC.channelData = self.channelData
6     }

1 //点击事件
2     func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
3         //what is do this
4         var rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
5         let channelId:AnyObject = rowData["channel_id"] as AnyObject
6         let channel:String = "channel=\(channelId)"
7         delegate?.onChangeChannel(channel)
8         self.dismissViewControllerAnimated(true, completion: nil)
9     }

5.MP3在线播放

 1 //定义一个播放器
 2     var audioPlayer:MPMoviePlayerController = MPMoviePlayerController()
 3
 4 //设置音乐
 5     func onSetAudio(url:String) {
 6         timer?.invalidate()
 7         timeLabel.text = "00:00"
 8
 9         self.audioPlayer.stop()
10         self.audioPlayer.contentURL = NSURL(string:url)
11         self.audioPlayer.play()
12         timer = NSTimer.scheduledTimerWithTimeInterval(0.4 , target : self, selector : "onUpdate", userInfo: nil, repeats :true)
13
14         playBtn.removeGestureRecognizer(tap)
15         logo.addGestureRecognizer(tap)
16         playBtn.hidden = true
17     }

6.TableView列表Item的出现动画

1 func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
2         cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
3         UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
4     }

7.UI控件汇总

 1 UIViewController
 2 UITableViewDataSource
 3 UITableViewDelegate
 4 UIImageView
 5 UILabel
 6 UIButton
 7 UIProgressView
 8 UITableView
 9 UITapGestureRecognizer
10 UIImage
11 MediaPlayer

8.最后把代码贴出来以供学习

  1 import UIKit
  2 import MediaPlayer
  3 import QuartzCore
  4
  5 class ViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate, HttpProtocol, ChannelProtocol{
  6
  7     @IBOutlet var logo: UIImageView
  8     @IBOutlet var timeLabel: UILabel
  9     @IBOutlet var buttonNext: UIButton
 10     @IBOutlet var progressBar: UIProgressView
 11     @IBOutlet var itemLayout: UITableView
 12     //开始点击事件
 13     @IBOutlet var tap: UITapGestureRecognizer = nil //这里必须为空,否则报错
 14
 15     @IBOutlet var playBtn: UIImageView
 16
 17
 18     //to cache the picture of songs
 19     var imageCache = Dictionary<String, UIImage>()
 20
 21     var eHttp:HttpController = HttpController()
 22     //主界面
 23     var tableData:NSArray =  NSArray()
 24     //频道列表
 25     var channelData:NSArray = NSArray()
 26     //定义一个播放器
 27     var audioPlayer:MPMoviePlayerController = MPMoviePlayerController()
 28
 29     var timer:NSTimer?
 30
 31     @IBAction func onTap(sender: UITapGestureRecognizer) {
 32         if sender.view == playBtn {
 33             playBtn.hidden = true
 34             audioPlayer.play()
 35             playBtn.removeGestureRecognizer(tap)
 36             logo.addGestureRecognizer(tap)
 37         } else if sender.view == logo{
 38             playBtn.hidden = false
 39             audioPlayer.pause()
 40             playBtn.addGestureRecognizer(tap)
 41             logo.removeGestureRecognizer(tap)
 42         }
 43     }
 44
 45     override func viewDidLoad() {
 46         super.viewDidLoad()
 47         //视图加载完之后,获取数据
 48         eHttp.delegate = self
 49         eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
 50         eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=0")
 51         progressBar.progress = 0.0
 52         logo.addGestureRecognizer(tap)
 53
 54     }
 55
 56     override func didReceiveMemoryWarning() {
 57         super.didReceiveMemoryWarning()
 58         // Dispose of any resources that can be recreated.
 59     }
 60
 61
 62     func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
 63         cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
 64         UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
 65     }
 66
 67
 68
 69     //TODO
 70     override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
 71         var channelC:ChannelController = segue.destinationViewController as ChannelController
 72         channelC.delegate = self// What TODO
 73         channelC.channelData = self.channelData
 74     }
 75
 76     func onChangeChannel(channelId:String) {
 77         let url:String = "http://douban.fm/j/mine/playlist?\(channelId)"
 78         eHttp.onSearch(url)
 79     }
 80
 81     func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
 82         return tableData.count
 83     }
 84     //列表展示
 85     func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
 86         let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "songs")
 87         let rowData:NSDictionary = self.tableData[indexPath.row] as NSDictionary
 88         cell.text = rowData["title"] as String
 89         cell.detailTextLabel.text = rowData["artist"] as String
 90         //默认图片
 91         cell.image = UIImage(named:"detail.jpg")
 92         //缩略图
 93         let url = rowData["picture"] as String
 94         let image = self.imageCache[url] as? UIImage
 95         if !image?{// why do this
 96             let imgURL:NSURL = NSURL(string:url)
 97             let request:NSURLRequest = NSURLRequest(URL:imgURL)
 98             NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
 99                 let img = UIImage(data:data)
100                 cell.image = img
101                 //缓存图片
102                 self.imageCache[url] = img
103                 })
104         } else {// if no this else, the item will be default image
105             cell.image = image
106         }
107
108         return cell
109     }
110
111     func didRecieveResults(results:NSDictionary) {
112         //println(results);
113         if(results["channels"]) {
114             self.channelData = results["channels"] as NSArray
115             //self.itemLayout.reloadData()
116         } else if(results["song"]) {
117             self.tableData = results["song"] as NSArray
118             self.itemLayout.reloadData()
119
120             let firDict:NSDictionary = self.tableData[0] as NSDictionary
121             let audioUrl:String = firDict["url"] as String
122             onSetAudio(audioUrl)
123             let imgUrl:String = firDict["picture"] as String
124             onSetImage(imgUrl)
125         }
126
127     }
128
129
130
131     func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
132         let rowData:NSDictionary = self.tableData[indexPath.row] as NSDictionary
133         let audioUrl:String = rowData["url"] as String
134         onSetAudio(audioUrl)
135         let imgUrl:String = rowData["picture"] as String
136         onSetImage(imgUrl)
137     }
138
139
140     //设置音乐
141     func onSetAudio(url:String) {
142         timer?.invalidate()
143         timeLabel.text = "00:00"
144
145         self.audioPlayer.stop()
146         self.audioPlayer.contentURL = NSURL(string:url)
147         self.audioPlayer.play()
148         timer = NSTimer.scheduledTimerWithTimeInterval(0.4 , target : self, selector : "onUpdate", userInfo: nil, repeats :true)
149
150         playBtn.removeGestureRecognizer(tap)
151         logo.addGestureRecognizer(tap)
152         playBtn.hidden = true
153     }
154
155     func onUpdate() {
156         let c = audioPlayer.currentPlaybackTime
157         if c > 0.0 {
158             let t = audioPlayer.duration
159             let p:CFloat=CFloat(c/t)
160
161             progressBar.setProgress(p, animated: true)
162
163             let allSecond:Int = Int(c)
164             let s:Int = allSecond%60
165             let m:Int = Int(allSecond/60)
166             var time:String = ""
167             if(m < 10) {
168                 time = "0\(m)"
169             } else {
170                 time = "\(m)"
171             }
172             if(s < 10) {
173                 time += ":0\(s)"
174             } else {
175                 time += ":\(s)"
176             }
177             timeLabel.text = time
178
179         }
180     }
181
182
183     //设置图片
184     func onSetImage(url:String) {
185         let image = self.imageCache[url] as? UIImage
186         if !image?{// why do this
187             let imgURL:NSURL = NSURL(string:url)
188             let request:NSURLRequest = NSURLRequest(URL:imgURL)
189             NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
190                 let img = UIImage(data:data)
191                 self.logo.image = img
192                 //缓存图片
193                 self.imageCache[url] = img
194                 })
195         } else {// if no this else, the item will be default image
196             self.logo.image = image
197         }
198
199     }
200
201 }

 1 import UIKit
 2
 3
 4 protocol HttpProtocol {
 5     func didRecieveResults(results:NSDictionary)
 6 }
 7
 8 class HttpController : NSObject {
 9
10     var delegate:HttpProtocol?
11
12     func onSearch(url:String) {
13         var nsUrl:NSURL = NSURL(string:url)
14         var request:NSURLRequest = NSURLRequest(URL:nsUrl)
15         //1.Closure Expression Syntax
16         //2.异步获取数据
17
18         NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{(response:NSURLResponse!, data:NSData!, error:NSError!)->Void in
19             var jsonResult:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
20             //why just miss an excalmatory mark, the code isn't compile
21             //self.delegate?.didRecieveResults(jsonResult)
22         })
23     }
24 }

 1 import UIKit
 2 import QuartzCore
 3
 4 protocol ChannelProtocol {
 5     func onChangeChannel(channelId:String)// why is String, is not NSString
 6 }
 7
 8 class ChannelController: UIViewController, UITableViewDataSource, UITableViewDelegate {
 9
10     @IBOutlet var listLayout: UITableView
11
12     var channelData:NSArray = NSArray()
13     var delegate:ChannelProtocol?
14
15     override func viewDidLoad() {
16         super.viewDidLoad()
17         // Do any additional setup after loading the view, typically from a nib.
18     }
19
20     override func didReceiveMemoryWarning() {
21         super.didReceiveMemoryWarning()
22         // Dispose of any resources that can be recreated.
23     }
24
25
26    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
27         return 10
28     }
29
30     func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
31         cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
32         UIView.animateWithDuration(0.25, animations:{cell.layer.transform=CATransform3DMakeScale(1, 1, 1)})
33     }
34
35     func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
36         let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "channel")
37         let rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
38         cell.text = rowData["name"] as String
39         return cell
40     }
41
42     func tableView(tableView:UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
43         //what is do this
44         var rowData:NSDictionary = self.channelData[indexPath.row] as NSDictionary
45         let channelId:AnyObject = rowData["channel_id"] as AnyObject
46         let channel:String = "channel=\(channelId)"
47         delegate?.onChangeChannel(channel)
48         self.dismissViewControllerAnimated(true, completion: nil)
49     }
50
51
52 }

转载于:https://www.cnblogs.com/royi123/p/3980012.html

[Swift A] - 实战-豆瓣电台总结相关推荐

  1. Swift实战-豆瓣电台(六)视图跳转,传参及回跳

    原文:Swift实战-豆瓣电台(六)视图跳转,传参及回跳 youku观看地址:http://v.youku.com/v_show/id_XNzMxMzQ3MDcy.html 要点 在ChannelCo ...

  2. Swift实战-豆瓣电台(八)播放进度与时间

    视频观看地址:http://www.tudou.com/programs/view/4mEtz8S72k0/?resourceId=399000367_06_02_99 这节主要内容是NSTimer, ...

  3. Swift实战-豆瓣电台(一)准备

    原文:Swift实战-豆瓣电台(一)准备 一 准备 我们现在看看我们要做一个什么样的东西 观看地址:http://v.youku.com/v_show/id_XNzI4ODY2Mjky.html 布局 ...

  4. Swift实战-豆瓣电台(三)获取网络数据

    原文:Swift实战-豆瓣电台(三)获取网络数据 观看地址:http://v.youku.com/v_show/id_XNzMwMzQxMzky.html 这节内容,我们先说了怎么将storyboar ...

  5. Swift实战-豆瓣电台(四)歌曲列表的展现

    原文:Swift实战-豆瓣电台(四)歌曲列表的展现 观看地址 http://v.youku.com/v_show/id_XNzMwNDE0OTA4.html 这节的主要内容是如何利用cell展现获取到 ...

  6. swift实战-豆瓣电台

    http://www.swiftv.cn/secure/course/hwxktqix/learn#lesson/hwxktqix0.61494483961723740.033873706357553 ...

  7. 《Swift开发实战》——第2章,第2.4节函数和闭包

    本节书摘来自异步社区<Swift开发实战>一书中的第2章,第2.4节函数和闭包,作者 李宁,更多章节内容可以访问云栖社区"异步社区"公众号查看 2.4 函数和闭包 在本 ...

  8. 买了一本老镇的swift语言实战晋级

    为什么80%的码农都做不了架构师?>>>    买的老镇的<<swift语言实战晋级>>书刚到,发现没有51CTO的100金币学习卡. 转载于:https:/ ...

  9. 《Swift开发实战》——第16章,第16.2节下标脚本用法

    本节书摘来自异步社区<Swift开发实战>一书中的第16章,第16.2节下标脚本语法,作者 李宁,更多章节内容可以访问云栖社区"异步社区"公众号查看 16.2 下标脚本 ...

最新文章

  1. System.Data.SqlClient.SqlException:“ ',' 附近有语法错误。必须声明标量变量 @Password。”
  2. 一起学微软Power BI系列-使用技巧(1)连接Oracle与Mysql数据库
  3. 单核工作法13:永不拖延(下)
  4. [TPYBoard - Micropython之会python就能做硬件 7] 学习使用蓝牙模块及舵机
  5. 【转载】COM 组件设计与应用(四)——简单调用组件
  6. 001. Ansible简介
  7. 再不懂ZooKeeper,就安安心心把这篇文章看完
  8. C语言课后习题(10)
  9. js中文件写入(字符串写入)_note
  10. Redis学习---(10)Redis 集合(Set)
  11. mybatis 复习笔记03
  12. CentOS7 MongoDB安裝
  13. 计算机网络原理之网络层(解疑答惑)
  14. html p标签嵌套a,HTML标签嵌套规则详细归纳适合新手朋友
  15. 3D 打印切片软件 CuraEngine 介绍
  16. laravel教程入门笔记
  17. NOR flash 坏块处理方法
  18. 推荐几个IDEA插件,Java开发者撸码神器。
  19. 【老鸟进阶】deepfacelab合成参数详解
  20. 王思聪麾下的HR,被刷屏了!

热门文章

  1. mysql导入txt_mysql怎么导入txt文件?
  2. Unity小技巧——Inspector中插入数组元素
  3. 阿里短信服务 JAVA
  4. 众创美业微信引流系统使用说明
  5. php cpu占有率过高怎么办,system占用cpu过高怎么办
  6. 二十五个摸鱼,哦,不对,是炫酷(可以玩一整天)的网站!!!
  7. 【正本清源】关于extern、static、const的正确使用方法
  8. java 消息签名_微信公众平台消息体签名及加解密实例(Java)
  9. sql查询最新时间的一条数据
  10. 冷暖自知!4年Java小伙收获美团Offer,分享他的社招Java岗4面面经