swift 4 使用小结(与OC差异比较大的写法)

    • 1. 懒加载
    • 2. 按钮的点击事件
    • 3. 协议可选与必选,delegate是否实现协议
    • 4. 判断是某个类或某个类及其子类
    • 5. tableView的刷新
    • 6. 正则匹配特定的图片链接
    • 7. swift中NSString的UTF-8转码
    • 8. GCD通信与延迟操作
    • 9. 数组中取子数组
    • 10. 通知
    • 11. 时间与时间戳
    • 12. 纯swift项目使用YYModel转模型问题
    • 13. 单例
    • 14. 访问库的差别
    • 15. 字符串映射类

1. 懒加载

   lazy var imageView:UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage.init(named: "big_image")
        return imageView
    }()

2. 按钮的点击事件

    lazy var button:UIButton = {
        let button = UIButton()
        button.setTitleColor(UIColor.red, for: .normal)
        button.backgroundColor = UIColor.white
        button.layer.cornerRadius = 2.0
        button.layer.masksToBounds = true
        button.isHidden = true
        button.addTarget(self, action: #selector(buttonClick(_ :)), for: .touchUpInside)
        return button
    }()

    @objc func buttonClick(_ button:UIButton) -> () {

    }

3. 协议可选与必选,delegate是否实现协议

  • 必选协议
protocol ImageViewDelegate: class {
    func selectedImage() -> ()
    func removeImage(_ index: Int) -> ()
}
  • 可选协议
@objc protocol ImageCellDelegate: NSObjectProtocol {
    @objc optional func imageCelllLikeButtonClick(imageCell: ImageCell, commentId: String, userLiked:Bool) -> ()
    @objc optional func imageCellDetalButtonClick(imageCell: ImageCell, content:String) -> ()
}
  • 代理
weak var delegate:ImageCellDelegate?

注意: 代理继承的父类 class和NSObjectProtocol 的区别

代理继承的父类NSObjectProtocol的时候,判断代理是否实现某个方法responds(to: #selector()能提示处理,继承自class则没法判断
ImageCellDelegate.实现的方法去判断!!!

  • 代理是否实现了某个协议
    @objc func buttonClick(_ button:UIButton) -> () {
        guard let delegate = delegate else { return }
        if delegate.responds(to: #selector(ImageCellDelegate.imageCellButtonClick(imageCell:content:))) {
            delegate.imageCellButtonClick!(imageCell: self, content: commentLabel.text)
        }
    }

4. 判断是某个类或某个类及其子类

//判断某个类
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.isMember(of: tableView.classForCoder) {
            view.endEditing(true)
        }
    }

//判断某个类及其子类
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.isKind(of: tableView.classForCoder) {
            view.endEditing(true)
        }
    }

5. tableView的刷新

//刷新所有
self.tableView.reloadData()
//刷新分组
self.tableView.reloadSections([1], with: .none)
//刷新某一个cell或者几个cell
self.tableView.reloadRows(at: [indexPath], with: .none)

6. 正则匹配特定的图片链接

class func getTopicContentImageUrlLink(_ range: NSRange, _ pattern: String = "", _ content: String) -> [URL] {     
        var imageUrlArr: [URL] = []

        //利用正则匹配
        let pattern = pattern
        guard let regularExpression = try? NSRegularExpression.init(pattern: pattern, options: .dotMatchesLineSeparators) else { return []}
        let regularResults = regularExpression.matches(in: content, options: [], range: NSMakeRange(0, content.count))

        for textCheckingResult in regularResults {
            //查找到的范围数量
            // 0: 和匹配方案完全一致的字符串
            // 1: ()中需要匹配的字符串
            for idx in 0..let range = textCheckingResult.rangeAt(idx)
                let subStr = (content as NSString).substring(with: range)
                let url = URL(string: subStr)
                if idx == 1 && url != nil {
                    imageUrlArr.append(url!)
                }
            }
        }
        return imageUrlArr
    }

7. swift中NSString的UTF-8转码

let content = (newString as NSString).addingPercentEscapes(using: String.Encoding.utf8.rawValue)!

8. GCD通信与延迟操作

        //线程通信
        DispatchQueue.global().async {
            //do async something
            DispatchQueue.main.async {
                //main thread do UI update
            }
        }
        //延迟操作  DispatchTime 的精度是纳秒
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10) {

        }
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 10) {

        }
        //DispatchWallTime 的精度是微秒
        DispatchQueue.global().asyncAfter(wallDeadline: DispatchWallTime.now() + 2.0) {

        }

9. 数组中取子数组

let arr = [1,2,3,4,5]
//是个切片数组和数组之间可以转化
let arrSlice = arr[0..<3]
let subArr = Array(arrSlice)

10. 通知

//通知名称
let ZQPCouponCellSelectedCoupon: Notification.Name = Notification.Name(rawValue: "ZQPCouponCellSelectedCoupon")
//发通知
NotificationCenter.default.post(name: ZQPCouponCellSelectedCoupon, object: couponModel)
//接通知
NotificationCenter.default.addObserver(self, selector: #selector(selectedCoupon(_ :)), name: ZQPCouponCellSelectedCoupon, object: nil)
//响应事件
@objc func selectedCoupon(_ notication: Notification) {
    let couponModel = notication.object as! ZQPPlanPlayRedEnvelopeModel
}

11. 时间与时间戳

//当前时间---毫秒级 时间戳 - 13位
let timeInterval: TimeInterval = Date().timeIntervalSince1970
let currentMillisecond = CLongLong(round(timeInterval*1000))
print(currentMillisecond)

`1532068608613`

//当前时间---秒级 时间戳 - 10位
let timeInterval: TimeInterval = Date().timeIntervalSince1970
let currentSecond = Int(timeInterval)
print(currentSecond)

`1532068723`

12. 纯swift项目使用YYModel转模型问题

属性前+@objc,否则字典转模型不成功

class PersonModel: NSObject {
    //姓名
    @objc var name: String?
    //年龄
    @objc var age: Int = 0
}

13. 单例

static let sharedInstance = ZYManagerController()

14. 访问库的差别

//OC
#import 

//Swift
import UIKit.UIGestureRecognizerSubclass

15. 字符串映射类

//注意,确保string有值,否则每一步转换,都要guard防卫
let childrenControllerString: String = item[RootVcName] as! String
let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
let childrenControllerClass = NSClassFromString(nameSpace + "." + childrenControllerString)
let childrenControllerType = childrenControllerClass as! UIViewController.Type
let childrenController = childrenControllerType.init()

你可能感兴趣的:(Swift,2.0~4.2,iOS开发)