Swift小技巧(八)

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
    }
}
Swift小技巧(八)_第1张图片
屏幕快照 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)
    }
}

效果:

Swift小技巧(八)_第2张图片
屏幕快照 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

你可能感兴趣的:(Swift小技巧(八))