1.如何播放視頻
//必須要:導入AVKit,導入AVFoundation
//即使您使用AVPlayer,也需要AVFoundation框架
//如果要使用AVPlayerViewController:
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
//如果只是AVPlayer:
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
2.如何快速求出一個數組內元素的綜合
let multiples = [...]
sum = multiples.reduce(0, +)
3.如何判斷掃動手勢掃動的方向
override func viewDidLoad() {
super.viewDidLoad()
//掃動的方向
let directions: [UISwipeGestureRecognizerDirection] = [.right, .left, .up, .down]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
//需要指定一下掃動的方向
gesture.direction = direction
view.addGestureRecognizer(gesture)
}
}
func handleSwipe(sender: UISwipeGestureRecognizer) {
//方向
print(sender.direction)
}
4.如何讓程序在睡眠指定時間
//當前線程睡眠延時10S
sleep(10)
5.如何判斷字符串前綴和后綴
let str = "aaa.com"
//前綴
str.hasPrefix("aa")//true
str.hasPrefix("cc")//false
//后綴
str.hasSuffix("com")//true
str.hasSuffix("cm")//false
6.swift中如何使用正則表達式
//擴展一個正則方法
extension String {
//只需要傳入正則表達式即可
func matches(regex: String) -> [String] {
do {
//生成正則對象
let regex = try NSRegularExpression(pattern: regex)
//轉換成nsstring
let nsString = self as NSString
//開始匹配,獲得匹配到的字符串的位置信息
let results = regex.matches(in: self, range: NSRange(location: 0, length: nsString.length))
//通過位置信息,獲得字符串
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("無效的正則表達式: \(error.localizedDescription)")
return []
}
}
}
//使用
let string = "8fdg9d"
string.matches(regex: "[0-9]")
7.如何讓label的高度自適應text的內容
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: view.frame.height))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = UIFont(name: "Helvetica", size: 20.0)
label.text = "很長很長很"
label.backgroundColor = .green
//加上sizeToFit即可,注意sizeToFit的位置!!!!
label.sizeToFit()
view.addSubview(label)
8.為什么CGFloat轉換成Float不能用as
let a: CGFloat = 0.11
let b: Float = a as Float//會報錯
let c: Float = Float(a)//正常
為什么會報錯呢,那是因為as是用于子類關系時,CGFloat和Float都不是彼此的子類,所以需要創建一個新的實例才可以。
9.如何獲得彈出的鍵盤的高度
//增加一個鍵盤彈起的監聽
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
func keyboardWillShow(notification: Notification) {
if let keyboardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
print("鍵盤的高度:\(keyboardSize.height)")
}
}
10.如何使用collection view實現均勻的網格布局
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var collectionView: UICollectionView?
var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
screenSize = UIScreen.main.bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth / 3, height: screenWidth / 3)
//需要添加下面兩句代碼,讓左右間距和上下間距都為0
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView!.backgroundColor = UIColor.green
self.view.addSubview(collectionView!)
}
//如果要讓第一個單元格占據整行寬度
// func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// if indexPath.row == 0 {
// return CGSize(width: screenWidth, height: screenWidth/3)
// }else {
// return CGSize(width: screenWidth/3, height: screenWidth/3)
// }
// }
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as UICollectionViewCell
cell.backgroundColor = UIColor.white
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 0.5
cell.frame.size.width = screenWidth / 3
cell.frame.size.height = screenWidth / 3
return cell
}
}
屏幕快照 2017-05-18 下午1.28.01.png
11.怎么使用一個值,初始化出一個數組,數組內元素都為該值
var array = [Int](repeatElement(10, count: 10))
12.如何在函數內部定義一個類似OC里面的全局變量
在函數內部,不能像OC一樣,使用static來聲明一個全局變量。但是可以如下實現效果。將全局變量聲明到一個結構體中。
func fun() {
struct Holder {
static var timesCalled = 0
}
Holder.timesCalled += 1
print("第\(Holder.timesCalled)次調用")
}
fun()//第1次調用
fun()//第2次調用
fun()//第3次調用
13.如何獲得一個數組內的最大值和最小值
let arr = [1,2,3,4,5,6,7]
arr.max()//7
arr.min()//1
14.如何實現自定義打印Log,打印出自定義的需要的數據
/*
#file(String)它顯示的文件的名稱。
#line(Int)出現的行號。
#column(Int)它開始的列號。
#function(String)它出現的聲明的名稱。
*/
func YHLog(_ object: Any?, filename: String = #file, line: Int = #line, funcname: String = #function) {
//if DEBUG的作用是,如果是調試模式才打印,否則,不打印
#if DEBUG
print("****\(Date()) \(filename)(\(line)) \(funcname):\r\(object ?? "nil")\n")
#endif
}
//使用
YHLog("這是一段文字")
15.如何實現一個view有梯度的顯示顏色
extension UIView {
//擴展一個方法
func layerGradient() {
let layer: CAGradientLayer = CAGradientLayer()
layer.frame = bounds
layer.colors = [UIColor.blue.cgColor, UIColor.red.cgColor]
//顏色位置
layer.locations = [0, 1]
//開始位置和結束位置
layer.startPoint = CGPoint(x: 0, y: 1)
layer.endPoint = CGPoint(x: 1, y: 1)
self.layer.insertSublayer(layer, at: 0)
}
}
效果:
屏幕快照 2017-05-20 下午4.14.31.png
16.如何在協議中,定義一個通用函數,可以傳入或傳出任意參數,遵循協議的類型自己定義參數類型
protocol Api {
associatedtype T
associatedtype U
func Map(Content: T) -> U
}
class User: Api {
typealias T = Int
typealias U = String
func Map(Content: Int) -> String {
return String(Content)
}
}
let user = User()
print(user.Map(Content: 10))
17.如何實現json格式字符串與dic之間的轉換,同理可以得到array之間的轉換
//json->dic
func converToDic(json: String) -> [String: Any]? {
if let data = json.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
}catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"Job\"}"
let dic = converToDic(json: str)
print(dic)
//dic->json
func converToJson(dic: [String: Any]) -> String? {
do {
let data = try JSONSerialization.data(withJSONObject: dic, options: [])
return String(data: data, encoding: .utf8)
} catch {
print(error.localizedDescription)
return nil
}
}
let json = converToJson(dic: dic!)
print(json)
18.如何獲得根視圖控制器
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController
19.如何通過數組index獲得數組內某個元素
class A {
var name: String?
init(name: String) {
self.name = name
}
}
let arr = [A(name: "a"), A(name: "b")]
//通過index方法獲得
if let i = arr.index(where: { $0.name == "a" }) {
print(arr[i].name)
}
20.iPhone輸入的時候,自動更正輸入,如何取消
textField.autocorrectionType = .no