美文网首页
Swift 编程和 OC 编程区别小记

Swift 编程和 OC 编程区别小记

作者: 浅寒 | 来源:发表于2017-09-11 17:46 被阅读0次
    1. edgesForExtendedLayout 设置为 None
    • OC

      self.edgesForExtendedLayout = UIRectEdgeNone;
      
    • Swift

      // Swift 没有 None 选项,通过初始化设置
      self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
      或
      edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)    // 编码规范(风格)区别
      

    由于导航栏是半透明的,设置为 None 时会显示黑色,需要设置self.navigationController.navigationBar.translucent = NO; 或navigationController?.navigationBar.isTranslucent = false

    1. 自定义 UIView 底层支持图层(CALayer),这里以设置为 AVPlayerLayer 为例
    • OC

      // 重写类方法
      + (Class)layerClass {
          return [AVPlayerLayer class]
      }
      // 在需要的地方设置图层的相关的属性,avPlayer = AVPlayer()
      [(AVPlayerLayer *)[self layer] setPlayer:avPlayer];
      
    • Swift

      override class var layerClass: AnyClass  {
         get {
             return AVPlayerLayer.self
         }
      }
      // 设置属性
      guard let avPlayerLayer = self.layer as? AVPlayerLayer else {
          return
      }
      avPlayerLayer.player = avPlayer
      
    1. 通过类名字符串初始化对象,以 HomeViewController 为例
    • OC

      NSString *className = @"HomeViewController";
      HomeViewController *homeViewController = [[NSClassFromString(className) alloc] init];
      
    • Swift

      let classString = "HomeViewController"
      let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + classString // 这里项目名不能带有下划线 “_” 或 “*” 等特殊字符
      let viewControllerClass = NSClassFromString(className) as! UIViewController.Type
      let homeViewController  = viewControllerClass.init()
      
    1. 单例模式实现
    • OC

      static Singleton* _instance = nil;  
      + (instancetype) shareInstance {  
          static dispatch_once_t onceToken ;  
          dispatch_once(&onceToken, ^{  
          _instance = [[self alloc] init] ;  
          }) ;   
         return _instance ;  
      } 
      
    • Swift

      final class Singleton {
         private init() { }
         static let shared = Singleton()
      }
      
    1. 获取字典中的键、值
    • OC

      NSDictionary *dictionary = [@"key": @"value"];
      NSArray *keys = dictionary.allKeys;
      
    • Swift

      let dictionary = ["key": "value"]
      let keys = Array(dictionary.keys)  // 这里 dictionary.keys 不再是数组,需要再转换
      

    未完待续,欢迎补充

    相关文章

      网友评论

          本文标题:Swift 编程和 OC 编程区别小记

          本文链接:https://www.haomeiwen.com/subject/aeyfsxtx.html