Swift学习练手中的点点滴滴

565 阅读2分钟

1、NSClassFromString

guard let workName = Bundle.main.infoDictionary!["CFBundleExecutable"] else {
    print("命名空间不存在")
    return
}
let cls: AnyClass? = NSClassFromString("\(workName as! String).\(vcs[indexPath.row])")
guard let vc = cls as? UIViewController.Type else {
    print("转成VC失败")
    return
}
navigationController?.pushViewController(vc.init(), animated: true)

使用 NSClassFromString 时,需要拼接 项目名称,否则返回为nil,因为 存在 命名空间的原因

2、Timer

计时器,监听 count,使用didSet,相应的,还有 willSet方法

var count: Float = 0.0 {
    didSet(oldValue) {
        view1.text = String(format: "%.1f", count)
    }
}

这里使用到了,如何只打印一位小数。

暂停定时器

@objc func end() {
    if state == .end {
        return
    }
    state = .end
    timer?.fireDate = Date.distantFuture // **
}

继续定时器

@objc func start() {
    if state == .start {
        return
    }
    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(change), userInfo: nil, repeats: true)
    }
    state = .start
    timer?.fireDate = Date.distantPast
}

重置

@objc func reset() {
    if state == .reset {
        return
    }
    state = .reset
    count = 0.0
    timer?.invalidate()
    timer = nil
}

@objc 表示 这是一个 oc的方法,因为 button 在初始化时,添加方法

    view2.addTarget(self, action: #selector(start), for: .touchUpInside)

要注意 timer的循环引用,可以采用oc的方法。判断页面有没有释放,在如下方法内打印判断

deinit {
    print("deinit")
}

3、类的命名

oc和swift的命名规范中提到,不能以数字开头,偶然新建了个文件,叫 3DTouchVC.swift,发现内部生成的 类名为 _DTouchVC,还能用

4、初始化

重写 ViewController 的 init方法时,一直提示 要

'required' initializer 'init(coder:)' must be provided by subclass of 'UIViewController'

必要初始化器,UIView系列的类,UIViewController系列的类,要添加,是因为 这些类 遵守 NSCoding protocol。

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

Swift 中构造方法比较严格,主要关键字有 Designated,Convenience,Required。

Designated,指定的,首要,每个类至少一个,子类可继承 父类的。

Convenience,便利的,优先级第二,必须在同一个类中使用,内部self.init,子类不能继承

Required,子类必须实现父类的构造方法

class Animal {
    var type: String
    var name: String
    
    // designated,子类可以继承
    init(_ type: String, name: String) {
        self.type = type
        self.name = name
    }

    // 需要子类必须继承的
    required init(_ type: String) {
        self.type = type
        self.name = ""
    }

    // 子类不能继承
    convenience init(name: String) {
        self.init("", name: name)
    }
}

class Dog: Animal {
    override init(_ type: String, name: String) {
        super.init(type, name: name)
    }
    
    required init(_ type: String) {
        super.init(type)
    }
}

未完待续。。。