美文网首页tom
ChiOS-我的Swift学习笔记

ChiOS-我的Swift学习笔记

作者: ChiOS | 来源:发表于2016-12-05 12:30 被阅读310次

    1. 怎样自定义初始化方法?

    convenience init(by name: ee) {
        self.init(name: ee, bundle: nil)
    }
    

    2. 怎样写一个单例?

    final class UserInfoManager {
        private init() {}
        static let shared = UserInfoManager()
    }
    

    3. 使用Realm的object,属性一定要是dynamic的,否则查询成功以后model不能取到值

    import UIKit
    import RealmSwift
    class UserLoginInfoModel: Object {
        dynamic var cardNum: String!
        dynamic var companyId: String!
        dynamic var companyName: String!
        dynamic var userId: String!
        override static func primaryKey() -> String? {
            return "userId"
        }
    }
    

    4. 如何使用响应链来处理多层视图的事件

    参考链接 http://www.cocoachina.com/ios/20161205/18282.html

    import Foundation
    import UIKit
    extension UIResponder {
        func handOutAction(by identifier: String, sender: Any!) {
            if !responderRouterActionChain(by: identifier, sender: sender) {
                guard let nextResponder = next else { return }
                nextResponder.handOutAction(by: identifier, sender: sender)
            }
        }
    
        internal func responderRouterActionChain(by identifier: String, sender: Any!) -> Bool {
            return false
        }
    }
    

    Demo地址:https://github.com/NirvanAcN/2017DayDayUp (Day2)

    5. 关于Realm使用工程中的.realm文件

    参考链接 https://realm.io/docs/swift/latest/#other-realms

    在工程中可能需要拖入一些.realm文件来读取一些配置或者静态数据。这时候使用如下代码是无法读取Test.realm文件的(模拟器可以读取)

    guard let fileURL = Bundle.main.url(forResource: "Test", withExtension: "realm") else {
        return
    }
    let realm = try! Realm.init(fileURL: fileURL)
    

    按照官网说明,只需要如下修改一下配置Configuration

    guard let fileURL = Bundle.main.url(forResource: "Test", withExtension: ".realm") else {
        return
    }
    let config = Realm.Configuration(fileURL: fileURL, readOnly: true)
    let realm = try! Realm(configuration: config)
    

    6. 获取最上层视图(keyWindow)

    参考链接 http://www.jianshu.com/p/3705caee6995

    let window = UIApplication.shared.keyWindow
    

    7. 怎样显示Playground的liveView?

    View - Assistant Editor - Show Assistant Editor
    快捷键组合 option + command + ↵

    8. 如何将A-Z/a-z存入数组?

    参考链接 http://blog.csdn.net/flyback/article/details/48268829

    let Acode = UnicodeScalar("A")!.value    //65
    let Zcode = UnicodeScalar("Z")!.value    //90
    let array = (Acode...Zcode).map { String(format: "%c", $0) }
    

    9.怎样判断代理实现了某个方法?

    借助optional

    protocol TestDelegate: NSObjectProtocol {
        func testFunction()
    }
    .
    .
    .
    weak var delegate: TestDelegate!
    delegate?.testFunction()
    

    10.怎样取消Button点击时的高亮状态?

    参考链接 http://www.jianshu.com/p/7eb016e4ceb1

    获取.allTouchEvents事件,将isHighlighted置否

    btn.addTarget(self, action: #selector(onBtnsAllAction), for: .allTouchEvents)
    .
    .
    .
    @objc private func onBtnsAllAction(_ sender: UIButton) {
        sender.isHighlighted = false
    }
    

    11.如何打印行数?

    print(#line)
    

    12.Realm支持什么数据格式?

    Bool    (作为Object属性必须有默认值)
    Int8
    Int16
    Int32
    Int64
    Double
    Float
    String  (不能保存超过 16 MB 大小的数据,optional)
    Date    (精度到秒)
    Data    (不能保存超过 16 MB 大小的数据)
    

    13.怎样在Attributes inspector中添加自定义属性?

    @IBDesignable
    @IBInspectable
    
    如图所示效果

    Demo地址:https://github.com/NirvanAcN/2017DayDayUp (Day1)

    14.获取农历

    let calendar = Calendar.init(identifier: .chinese)
    let date = Date()
    let localeComp = calendar.dateComponents([.year, .month, .day], from: date)
    
    print(localeComp.year)
    print(localeComp.month)
    print(localeComp.day)
    

    15.如何截屏

    UIGraphicsBeginImageContext(someView.bounds.size)
    someView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    16.使用YYModel过程中遇到 fatal error: NSArray element failed to match the Swift Array Element type 异常

    实现modelContainerPropertyGenericClass方法

    class OrderModel: NSObject, YYModel {
        var goods: [OrderGoodsModel]!
    
        static func modelContainerPropertyGenericClass() -> [String : Any]? {
            return [
                "ddxq": OrderGoodsModel.self
            ]
        }
    }
    
    class OrderGoodsModel: NSObject, YYModel {
    
    }
    

    17.Realm增加/删除/修改表字段

    修改完毕后需要在application(_:didFinishLaunchingWithOptions:)方法中对数据库的版本进行重新设置(默认schemaVersion为0,修改后的schemaVersion应大于原值):

    Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 0
    )
    

    18.应用内打开AppStore

    StoreKit

    19.ATS中设置例外(白名单)

    参考链接:http://www.cocoachina.com/ios/20150928/13598.html

    例如,允许来自 http://www.baidu.com 的相关链接进行http访问

    <key>NSAppTransportSecurity</key>  
      <dict>  
          <key>NSExceptionDomains</key>  
          <dict>  
              <key>www.baidu.com</key>  
              <dict>  
                  <key>NSExceptionAllowsInsecureHTTPLoads</key>  
                  <true/>  
              </dict>  
          </dict>  
      </dict>  
    

    20.Debug 标示符

    __FILE__ ->  #file
    __LINE__ -> #line
    __COLUMN__ -> #column
    __FUNCTION__ -> #function
    __DSO_HANDLE__ -> #dsohandle
    

    21.修改Status Bar颜色

    参考链接:http://www.jianshu.com/p/25e9c1a864be

    修改plist文件

        <key>UIStatusBarStyle</key>
        <string>UIStatusBarStyleLightContent</string>
        <key>UIViewControllerBasedStatusBarAppearance</key>
        <false/>
    

    22.修改了工程的BundleID后,运行产生Failed to load Info.plist from bundle错误

    错误截图

    参考链接 http://stackoverflow.com/a/42067502/7760667

    解决方案:重置模拟器
    Simulator —— Reset content and Setting...

    23.EXC_BAD_ACCESS?

    Scheme — Run — Diagnostics - Runtime Sanitization - Address Sanitizer
    

    24.测试未发布的Pod/不发布通过cocoapods使用git上的仓库

    参考链接 https://guides.cocoapods.org/making/making-a-cocoapod.html#testing

    You can test the syntax of your Podfile by linting the pod against the files of its directory, this won't test the downloading aspect of linting.

    $ cd ~/code/Pods/NAME$ pod lib lint
    

    Before releasing your new Pod to the world its best to test that you can install your pod successfully into an Xcode project. You can do this in a couple of ways:
    Push your podspec to your repository, then create a new Xcode project with a Podfile and add your pod to the file like so:

    pod 'NAME', :git => 'https://example.com/URL/to/repo/NAME.git'
    

    Then run

    pod install-- or --pod update
    

    25.发布的Pod搜索不到?

    pod setup
    rm ~/Library/Caches/CocoaPods/search_index.json
    

    26.Git如何删除远程tag?

    git tag -d 0.0.1
    git push origin :refs/tags/0.0.1
    

    27.怎样对异步函数进行单元测试

    参考链接 http://www.mincoder.com/article/3650.shtml

    func testShowMe() {
        /// Creates and returns an expectation associated with the test case.
        let exp = expectation(description: "my_tests_identifying")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            /// that vended the expectation has already completed.
            exp.fulfill()
        }
        /// are fulfilled or the timeout is reached. Clients should not manipulate the run
        waitForExpectations(timeout: 3, handler: nil)
    }
    

    28.怎样在多个异步操作完成后再执行指定操作

    参考链接 http://www.jianshu.com/p/6a7af360bf2a

    let group = DispatchGroup()
    let timeLine = DispatchTime.now()
    (0..<10).forEach({ (idx) in
        group.enter()
        DispatchQueue.main.asyncAfter(deadline: timeLine + TimeInterval(idx), execute: {
            group.leave()
        })
    })
    group.notify(queue: DispatchQueue.main) {
        /// finished
    }
    

    29.怎样在向上滑动时隐藏NavagationBar?

    hidesBarsOnSwipe = true
    

    30.设置NavagationBar背景透明?

    参考链接 http://www.jianshu.com/p/b2585c37e14b

    navigationBar.subviews[0].alpha = 0
    

    31.怎样在Framework/Pod中加载Xib、Storyboard 、图片等资源(加载Bundle)?

    参考链接 http://blog.csdn.net/ayuapp/article/details/54631592

    // 1. 暴露Framework的Class文件
    // 2. 使用public /*not inherited*/ init(for aClass: Swift.AnyClass)加载
    let bundle = Bundle.init(for: JRConfigurations.self)
    

    32.怎样将AVFoundation中AVCaptureMetadataOutput的rectOfInterest坐标转换为正常屏幕坐标?

    在AVCaptureSession执行startRunning()函数后,AVCaptureVideoPreviewLayer通过metadataOutputRectOfInterest方法转换即可得到转换后的坐标。

    33.查看、修改Git用户名、邮箱

    $ git config --global user.name "username"
    
    $ git config --global user.email "email"
    

    34.GIT追加的.gitignore规则不生效?

    $ git rm -r --cached .
    $ git add .
    $ git commit -m 'update .gitignore'
    

    35.怎样给一个Optional添加一个extension?

    extension Optional where Wrapped == String {
      var isBlank: Bool {
        return self?.isBlank ?? true
      }
    }
    

    36.怎样调整行间距?

    let des = NSMutableAttributedString.init(string: "hello world")
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 6
    des.addAttributes([NSParagraphStyleAttributeName: paragraphStyle], range: NSRange.init(location: 0, length: des.length))       
    label.attributedText = des
    
    附:NSMutableParagraphStyle其他属性
    行间距 
    CGFloat lineSpacing
    
    段间距 
    CGFloat paragraphSpacing
    
    对齐方式 
    NSTextAlignment alignment
    
    首行缩进
    CGFloat firstLineHeadIndent
    
    除首行之外其他行缩进
    CGFloat headIndent
    
    每行容纳字符的宽度
    CGFloat tailIndent
    
    换行方式
    lineBreakMode
    
    最小行高
    CGFloat minimumLineHeight
    
    最大行高
    CGFloat maximumLineHeight
    

    37.怎样判断一个对象是否在某个范围?

    let age = 27
    print(20...30 ~= age) /// true
    
    let score = [100, 99, 80, 66, 40]
    
    let filter = score.filter {
        return 90...100 ~= $0
    }
    print(filter) /// [100, 99]
    

    38.ASDK Flex属性?

    direction:
        ASStackLayoutDirectionVertical
        ASStackLayoutDirectionHorizontal
    
    justifyContent:
        ASStackLayoutJustifyContentStart
        ASStackLayoutJustifyContentEnd
        ASStackLayoutJustifyContentCenter
        ASStackLayoutJustifyContentSpaceBetween
        ASStackLayoutJustifyContentSpacAeround
    
    alignItems:
        ASStackLayoutAlignItemsStart
        ASStackLayoutAlignItemsEnd
        ASStackLayoutAlignItemsCenter
        ASStackLayoutAlignItemsBaselineFirst
        ASStackLayoutAlignItemsBaselineLast
        ASStackLayoutAlignItemsStretch
    

    39.ASDK Layout Specs规则?

    ASInsetLayoutSpec   
    ASOverlayLayoutSpec 
    ASBackgroundLayoutSpec  
    ASCenterLayoutSpec  
    ASRatioLayoutSpec   
    ASStackLayoutSpec   
    ASAbsoluteLayoutSpec    
    ASRelativeLayoutSpec
    ASWrapperLayoutSpec
    

    40.怎样设置ASCollecitonNode的header&footer?

    foo.registerSupplementaryNode(ofKind: UICollectionElementKindSectionFooter)
    
    func collectionNode(_ collectionNode: ASCollectionNode, nodeForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> ASCellNode {
        return ASCellNode()
    }
    
    func collectionNode(_ collectionNode: ASCollectionNode, sizeRangeForFooterInSection section: Int) -> ASSizeRange {
        return ASSizeRange()
    }
    

    41.搜索状态navigation bar上的search controller的search bar消失了?

    searchController.hidesNavigationBarDuringPresentation = false
    

    42.Xcode9 ScrollView下移?

            if #available(iOS 11.0, *) {
                view.contentInsetAdjustmentBehavior = .never
            } else {
                automaticallyAdjustsScrollViewInsets = false
            }
    

    43. ASDK设置间距

    nodeB.style.spaceBefore = 15
    

    44. 设置SSH连接

    $ ssh-keygen
    $ cat ~/.ssh/id_rsa.pub
    

    相关文章

      本文标题:ChiOS-我的Swift学习笔记

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