1. 程式人生 > >swift學習筆記

swift學習筆記

swift筆記

基礎知識

進位制

0x代表16進位制

0o代表8進位制

0b代表2進位制er

dict

dict: listdata
listdata.count 總數
for i in listdata{
print i.key
piint i.value
}

dict to array Array(dict.allkeys)
Array會打亂dict順序

拆包

可空型別 optional

如果一個值的宣告不是可空型別,說明他一定有值,保證了安全性

!申明為隱式可控型別

var a:String?
隱式轉換型別 如果沒有值就會導致執行錯誤
而 可空型別不需要

as?為可選型別 進行轉換 當轉換失敗時,值為nil

可以不必初始化,也就是說這個變數可能為nil
而且型別是String?型別

在輸出值是用!來解包

String

插入

var var_url=url

​ let off5=url.index(of: “:”)

​ var_url.insert(“s”, at: off5!)

輸出格式化

let format = String(format:”%.2f”,b)

對數字進行formate

 let times=String.init(format: “%02d:%02d”,mins,second)

向專案裡面新增別的庫函式

2 種辦法

cathage:

建立file 然後update

cocoaPods

pod search Snapkit

找出所有的包

然後vim profile
將內容加進去

然後pod install

xcodebuild -showsdks 檢視ios版本

cocoa

storyboard

建立storyboard 然後將空間拖入需要呼叫的swift中 

@IBOutlet weak var

然後如果要對按鈕繫結事件, @IBAction func

在storyboard中設定 table 的資料來源右鍵拖table 到最上邊的小黃點,然後選擇datasource

可以設定 多個storyboard連線,管理不同的module

設定searchDisplaycontroller

防止生成多餘的table_cell

        tableview.tableFooterView = UIView()

UItableview

如何設定響應,應該在設定delegate?

在extention 中新增 UITableViewDelegate 如果無效的話

將一個screen變成storyboard

針對第一個Demo,進行拆分,選中Contacts以及nav(高亮顯示),然後點選Xcode的選單欄,選擇”Editor->Refactor to Storyboard”。

設定動作變化動畫

animationWithDuration 動畫持續時間

animation 動畫閉包,在這個閉包中你可以改變UIView的各種動畫屬性。

元件位置:

改變元件位置

通過設定center的x和y來改變

設定元件位置:

        myslider=UISlider(frame: CGRect(x:20, y:380, width: 300, height: 20))

螢幕大小:

​ 375

​ 667

得到螢幕寬度:

 let fullsize=UIScreen.main.bounds.size

        let width=fullsize.width

        let height=fullsize.height

        print(width)

        print(height)

imageview

建立一個imageview 在目錄下建立個image資料夾,放入圖片

let imgArr=[UIImage(named: “1_13.jpg”)!,

UIImage(named: “1_31.jpg”)!,

UIImage(named: “imag.jpg”)!,

]

可以直接使用Assets.xcassets中的檔案

可以設定輪播

圖片旋轉

  • let rad=20/180*Float(Double.pi)

myImageView.transform=CGAffineTransform(rotationAngle: CGFloat(rad))

  • 連續旋轉

    let rad=20/180*Float(Double.pi)
    myImageView.transform=myImageView.transform.rotated(by: CGFloat(rad))

  • 按照週期不停旋轉

let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")

// // 2.設定動畫的屬性

// rotationAnim.fromValue = 0

// rotationAnim.toValue = M_PI * 2

// rotationAnim.repeatCount = MAXFLOAT

// rotationAnim.duration = 1

// // 這個屬性很重要 如果不設定當頁面執行到後臺再次進入該頁面的時候 動畫會停止

// rotationAnim.isRemovedOnCompletion = false

// // 3.將動畫新增到layer中

// myImageView.layer.add(rotationAnim, forKey: nil)

UIImageview的初始圖片
myImageView.image=UIImage( named: “angry/angry_00.jpg”)

animationDuration : 迴圈走一遍花費的時間

animationRepeatCount: 重複的次數

上下平移

通過center來上下平移
如果通過origin.x來平移
圖形在旋轉是會發生變化

放大和縮小

通過bounds.size.height 和bounds.size。width來放大和縮小 不然旋轉時會改變大小

設定cgrect 的介面為全屏

button

使用tag 向button傳值

 button1.addTarget(self, action: #selector(ViewController.play(sender:)), for: .touchUpInside)
 @objc func play(sender:UIButton) {

// tag==0 start

 if sender.tag==0{
 myImageView.startAnimating()
 }
}

slider

 myslider=UISlider(frame: CGRect(x:20, y:380, width: 300, height: 20))
 myslider.addTarget(self, action: #selector(valuechanged(_sender:)), for:UIControlEvents.valueChanged)

  myslider.minimumValue=0

  myslider.maximumValue=180

webview

webView=WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))

let request=URLRequest(url: url!)

webView.load(request)

載入html

func startLoad() {
    let url = URL(string: "https://www.example.com/")!
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            self.handleClientError(error)
            return
        }
        guard let httpResponse = response as? HTTPURLResponse,
            (200...299).contains(httpResponse.statusCode) else {
            self.handleServerError(response)
            return
        }
        if let mimeType = httpResponse.mimeType, mimeType == "text/html",
            let data = data,
            let string = String(data: data, encoding: .utf8) {
            DispatchQueue.main.async {
                self.webView.loadHTMLString(string, baseURL: url)
            }
        }
    }
    task.resume()
}

操縱網頁

goBack()
goForward()
reload()
stopLoading()

在swift中呼叫js方法
在js中 用 window.webkit.messageHandlers.Test.postMessage(text) 將資訊傳遞給swift

  • WKScriptMessageHandler 將網頁中的js資料傳遞過來
  • wkuiDelegate 將alter視窗攔截下來
    在swift中用

讀取檔案

  • 讀取圖片
    需要將圖片資料夾新增在沙盒中
    然後路徑讀取
  • 讀取plist
    從最原始的路徑開始讀
    let home=NSHomeDirectory() as NSString
    let arrayPath=home.strings(byAppendingPaths: [“tom.list”])
  • 從main沙盒路徑讀取
    undle 的全域性路徑
    /Users/fanjialiang2401/Library/Developer/CoreSimulator/Devices/F11FF9DC-A17A-4400-B7B7-BA8E33B4AE6B/data/Containers/Bundle/Application/C4CC4002-3574-48D7-ACBE-DB6A486510BB/Tom.app

  • 從當前目錄下讀取

    let budledir=Bundle.main.path(forResource: “tom”, ofType: “plist”)
    var listdata=NSDictionary(contentsOfFile: budledir!)

bug整理

  1. 當storyboard和lable繫結時,不能改名字,否則 會報錯:setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key feel_like.’

湯姆貓的實現思路

載入plist,從plist中讀取dict
然後給每個button設定label,然後從 dict[label]中讀取圖片的個數和檔案的路徑

然後將圖片載入到imageview中,來播放,播放的時間用animationDuration來設定

在imageview播放期間,如果點選了其他的按鈕,則返回,避免破壞播放

最終的專案

  1. 圖片瀏覽器

​ 功能要求:

​ 根據拖動滑動條來改變圖片的瀏覽順序

​ 根據圖片的改變動態改變圖片的文字描述

​ 增加一個滑動條實現圖片的放大和縮小

​ 實現夜間模式和白天模式的切換

  1. 天氣預報

    功能要求:

    全國一些城市的天氣預報顯示

    通過搜尋輸入框來進行天氣查詢,可支援全球3萬多城市的天氣查詢

    支援拼音查詢,漢字查詢

    支援詳細內容查詢,點選cell跳轉進入詳細內容的顯示,有風速,風向,體感溫度,實際溫度,溼度,氣壓等詳細資料的顯示

  2. 個人創新專案,私人fm

    實現音樂播放器功能:歌曲名,演唱者,圖片顯示,切換歌曲,拖動進度條功能

    採用豆瓣FM介面,可以向用戶隨機推薦歌曲。如果不喜歡即可切換下一首

  3. 圖片排列

    根據選擇的行數不同來排列不同的圖片

    實現視訊上的要求

  4. 瀏覽器,訪問蘋果官網的首頁