Apple Watch學習之路 基礎控制元件學習

wongstar發表於2017-12-14

工欲善其事必先利其器,watch中基本控制元件的學習是寫watch app的基石

WatchKit中的控制元件都繼承自WKInterfaceObject,都以WKInterface開頭。下面是apple watch 常用的控制元件: source demo 傳送門:https://github.com/wongstar/AppleWatchDemo

WKInterfaceGroup--->Group watch常用的控制元件,主要有水平和垂直兩個方向
WKInterfaceImage--->圖片
WKInterfaceMovie--->播放視訊相關
WKInterfaceLabel--->label 標籤
WKInterfacePicker --->時間選擇器
WKInterfaceTable--->table ui相關非常重要
WKInterfaceTimer--->timer時間
WKInterfaceSwitch--->switch選擇器
WKInterfaceSlider  --->slider一般用在音量大小
WKInterfaceButton  --->按鈕ui
WKInterfaceMap --->map地圖相關
複製程式碼

####WKInterfaceGroup使用

WKInterfaceGroup.png

如上圖所示:

  • 從控制元件版面中拉2個Group控制元件到UI中,把它們重新命名為Group1,Group2,然後分別拉2個button到Group1 Group2中
  • 點選Group1 設定Layout方向為Vertical ,裡面的item直接的間距設定Spacing =11.加入button 1 和button 2加入Group容器中。
  • 點選Group2 設定Layout方向horizontal ,裡面的item會水平排列。設定item直接的間距11 就直接調整Spacing
  • 設定Group中item的寬高,所以設定Width和Height為Fixed模式,然後填寫對應的寬高值。

####WKInterfaceTable使用 首先檢視下WatchOS 中WKInterfaceTable提供了哪些方法和屬性

open class WKInterfaceTable : WKInterfaceObject {
   open func setRowTypes(_ rowTypes: [String]) // row names. size of array is number of rows
    open func setNumberOfRows(_ numberOfRows: Int, withRowType rowType: String) // repeating row name----->必須要實現才能知道又多少rows
    open var numberOfRows: Int { get }---->獲取有多少rows
    open func rowController(at index: Int) -> Any? ---->必須實現遍歷每個row
    open func insertRows(at rows: IndexSet, withRowType rowType: String)--->insert rows 到tableview中去
    open func removeRows(at rows: IndexSet) ----->移除指定的row
    open func scrollToRow(at index: Int) ------>滑動到指定的row
    @available(watchOS 3.0, *)
    open func performSegue(forRow row: Int)  ---->watch os 3.0點選之後跳轉
}
複製程式碼

從storyboard UI控制元件區拉一個table到Interface中 如下圖所示

WKInterfaceTable.png

然後storyboard UI中table拉一個連結到TableController中,然後產生一個table引數

 @IBOutlet var table: WKInterfaceTable!
複製程式碼

接下來新建一個Cell.swfit 檔案

tableCell.png
如上圖所示:

  • 新建一個名為TestTableCell.swfit檔案.把tableview中的cell對應的Custom class指向該檔案
  • 加入WKInterfaceLabel 和WKInterfaceImage 2個物件到UI中,並且把這兩個連結指向TestTableCell中的兩個控制元件變數

TestTableCell.swfit 原始碼如下:

class TestTableCell: NSObject {
    @IBOutlet var leftTitle: WKInterfaceLabel!
    @IBOutlet var icon: WKInterfaceImage!
    var source:String?{
        didSet{
            leftTitle.setText(source);
            icon.setImage(UIImage.init(named: "like.png"))
        }
    }
}
複製程式碼

如上原始碼所示設定了一個變數source,在tableviewcell中設定值更新對應的label和image

對應的ui 的controller 名稱為:TestTableInterfaceController具體source如下:

     table.setNumberOfRows(sources.count, withRowType: "cellId")
        for index in 0..<table.numberOfRows{
            if let cell = table.rowController(at: index) as? TestTableCell {
                cell.source=sources[index]//call cell source 更新UI
            }
        }
複製程式碼

setNumberOfRows (sources.count, withRowType:"cellId")->設定有多少row 注意這裡cellId要在storyboard 要設定在Row Controller屬性中Identifier設定為cellId for index in 0..<table.numberOfRows -->遍歷sources中每個item table.rowController(at: index) 設定cell相關引數 index:為當前是第幾個row cell.source=sources[index]//call cell source 更新UI

那tableview item點選在watch os怎麼處理呢?

  • 第一種方式:通過storyBoard中拉線跳轉,通過segue push方式跳轉到其他的Interface,傳值的時候需要在InterfaceController實現下面方法
override func contextForSegue(withIdentifier segueIdentifier: String) -> Any?
複製程式碼
  • 第二種方式:我們可以重寫實現InterfaceController中的如下方法,來處理Table的點選事件
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int)
複製程式碼

####Audio Video 使用

  • 呼叫系統播放控制元件 通過self.presentMediaPlayerControllerWithURL方法來呼叫系統控制元件來實現播放。如下面程式碼:
let myBundle = NSBundle.mainBundle()
if let movieURL = myBundle.URLForResource("myMovie", withExtension: "mp4") {
    self.movie.setMovieURL(movieURL)
    
    self.presentMediaPlayerControllerWithURL(movieURL,
                                             options: [WKMediaPlayerControllerOptionsAutoplayKey: true],
                                             completion: { (didPlayToEnd : Bool,
                                                endTime : NSTimeInterval,
                                                error : NSError?) -> Void in
                                                if let anErrorOccurred = error {
                                                    // Handle the error.
                                                }
                                                // Perform other tasks
    })
    
}

複製程式碼

畫面UI見下圖:

movie介面.png

  • 通過WKInterfaceMovie控制元件 WKInterfaceMovie 物件是播放video 和audio控制元件,:
open class WKInterfaceMovie : WKInterfaceObject {
    open func setMovieURL(_ URL: URL)//把Video or Audio url的放入其中
    open func setVideoGravity(_ videoGravity: WKVideoGravity) // default is WKVideoGravityResizeAspec
//AVLayerVideoGravityResizeAspectFill: 這可以保留縱橫比,但填滿可用的螢幕區域,裁剪視訊必要時
    open func setLoops(_ loops: Bool)//是否迴圈播放
    open func setPosterImage(_ posterImage: WKImage?)//設定封面
}

Gravity的可以如下:
public enum WKVideoGravity : Int {
    case resizeAspect //
    case resizeAspectFill //全部平鋪
    case resize //實際size
}
複製程式碼

從storyBoard拉根線到TestMapInterfaceController.swift

@IBOutlet var myMovie: WKInterfaceMovie!
let moviePath=Bundle.main.path(forResource: "minion", ofType: "mp4")
if moviePath == nil{
            return ;
        }
let url = URL(fileURLWithPath:moviePath!)
if url == nil{
            return;
        }
self.myMovie.setMovieURL(url)//設定url
self.myMovie.setLoops(true)//設定迴圈播放
self.myMovie.setPosterImage(WKImage.init(imageName: "like.png"))//設定開始的封面
self.myMovie.setVideoGravity(WKVideoGravity.resizeAspect)//設定video播放的大小
複製程式碼

得出下面的UI

視訊.gif

  • Play Local Audio file 通過WKAudioFilePlayer播放本地的mp3檔案,通過WKAudioFileQueuePlayer 可以迴圈播放列表

audio_file.png

#####想隨時瞭解我的動態,請關注我的個人公眾號

蟻農之家.jpg

相關文章