ChiOS-我的Swift學(xué)習(xí)筆記

1. 怎樣自定義初始化方法?

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

2. 怎樣寫一個(gè)單例?

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. 如何使用響應(yīng)鏈來(lái)處理多層視圖的事件

參考鏈接 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. 關(guān)于Realm使用工程中的.realm文件

參考鏈接 https://realm.io/docs/swift/latest/#other-realms

在工程中可能需要拖入一些.realm文件來(lái)讀取一些配置或者靜態(tài)數(shù)據(jù)。這時(shí)候使用如下代碼是無(wú)法讀取Test.realm文件的(模擬器可以讀?。?/p>

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

按照官網(wǎng)說(shuō)明,只需要如下修改一下配置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://m.itdecent.cn/p/3705caee6995

let window = UIApplication.shared.keyWindow

7. 怎樣顯示Playground的liveView?

View - Assistant Editor - Show Assistant Editor
快捷鍵組合 option + command + ?

8. 如何將A-Z/a-z存入數(shù)組?

參考鏈接 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.怎樣判斷代理實(shí)現(xiàn)了某個(gè)方法?

借助optional

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

10.怎樣取消Button點(diǎn)擊時(shí)的高亮狀態(tài)?

參考鏈接 http://m.itdecent.cn/p/7eb016e4ceb1

獲取.allTouchEvents事件,將isHighlighted置否

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

11.如何打印行數(shù)?

print(#line)

12.Realm支持什么數(shù)據(jù)格式?

Bool    (作為Object屬性必須有默認(rèn)值)
Int8
Int16
Int32
Int64
Double
Float
String  (不能保存超過(guò) 16 MB 大小的數(shù)據(jù),optional)
Date    (精度到秒)
Data    (不能保存超過(guò) 16 MB 大小的數(shù)據(jù))

13.怎樣在Attributes inspector中添加自定義屬性?

@IBDesignable
@IBInspectable
如圖所示效果

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

14.獲取農(nóng)歷

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過(guò)程中遇到 fatal error: NSArray element failed to match the Swift Array Element type 異常

實(shí)現(xiàn)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:)方法中對(duì)數(shù)據(jù)庫(kù)的版本進(jìn)行重新設(shè)置(默認(rèn)schemaVersion為0,修改后的schemaVersion應(yīng)大于原值):

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

18.應(yīng)用內(nèi)打開AppStore

StoreKit

19.ATS中設(shè)置例外(白名單)

參考鏈接:http://www.cocoachina.com/ios/20150928/13598.html

例如,允許來(lái)自 http://www.baidu.com 的相關(guān)鏈接進(jìn)行http訪問(wèn)

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

20.Debug 標(biāo)示符

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

21.修改Status Bar顏色

參考鏈接:http://m.itdecent.cn/p/25e9c1a864be

修改plist文件

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

22.修改了工程的BundleID后,運(yùn)行產(chǎn)生Failed to load Info.plist from bundle錯(cuò)誤

錯(cuò)誤截圖

參考鏈接 http://stackoverflow.com/a/42067502/7760667

解決方案:重置模擬器
Simulator —— Reset content and Setting...

23.EXC_BAD_ACCESS?

Scheme — Run — Diagnostics - Runtime Sanitization - Address Sanitizer

24.測(cè)試未發(fā)布的Pod/不發(fā)布通過(guò)cocoapods使用git上的倉(cāng)庫(kù)

參考鏈接 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.發(fā)布的Pod搜索不到?

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

26.Git如何刪除遠(yuǎn)程tag?

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

27.怎樣對(duì)異步函數(shù)進(jìn)行單元測(cè)試

參考鏈接 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.怎樣在多個(gè)異步操作完成后再執(zhí)行指定操作

參考鏈接 http://m.itdecent.cn/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.怎樣在向上滑動(dòng)時(shí)隱藏NavagationBar?

hidesBarsOnSwipe = true

30.設(shè)置NavagationBar背景透明?

參考鏈接 http://m.itdecent.cn/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坐標(biāo)轉(zhuǎn)換為正常屏幕坐標(biāo)?

在AVCaptureSession執(zhí)行startRunning()函數(shù)后,AVCaptureVideoPreviewLayer通過(guò)metadataOutputRectOfInterest方法轉(zhuǎn)換即可得到轉(zhuǎn)換后的坐標(biāo)。

33.查看、修改Git用戶名、郵箱

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

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

34.GIT追加的.gitignore規(guī)則不生效?

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

35.怎樣給一個(gè)Optional添加一個(gè)extension?

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

36.怎樣調(diào)整行間距?

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

對(duì)齊方式 
NSTextAlignment alignment

首行縮進(jìn)
CGFloat firstLineHeadIndent

除首行之外其他行縮進(jìn)
CGFloat headIndent

每行容納字符的寬度
CGFloat tailIndent

換行方式
lineBreakMode

最小行高
CGFloat minimumLineHeight

最大行高
CGFloat maximumLineHeight

37.怎樣判斷一個(gè)對(duì)象是否在某個(gè)范圍?

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規(guī)則?

ASInsetLayoutSpec   
ASOverlayLayoutSpec 
ASBackgroundLayoutSpec  
ASCenterLayoutSpec  
ASRatioLayoutSpec   
ASStackLayoutSpec   
ASAbsoluteLayoutSpec    
ASRelativeLayoutSpec
ASWrapperLayoutSpec

40.怎樣設(shè)置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.搜索狀態(tài)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設(shè)置間距

nodeB.style.spaceBefore = 15

44. 設(shè)置SSH連接

$ ssh-keygen
$ cat ~/.ssh/id_rsa.pub
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,355評(píng)論 25 708
  • 不知何時(shí)起,春天就已經(jīng)來(lái)了。換上春裝,帶著手機(jī),乘陽(yáng)光正好去感受春的氣息。路遇一棵垂柳,迎面而來(lái)的就是一陣清新,枝...
    木子不愛(ài)糖閱讀 385評(píng)論 1 2
  • 一年前,大概是在六月底的時(shí)候,我在公交車上閱讀《約翰·克利斯朵夫》,讀到約翰和他的舅舅在一個(gè)空曠的田野中感受大自然...
    穩(wěn)泛滄浪閱讀 365評(píng)論 0 0
  • JSP 標(biāo)準(zhǔn)標(biāo)記庫(kù)(JSP Standard Tag Library,JSTL)是一個(gè)實(shí)現(xiàn) Web 應(yīng)用程序中常見...
    夢(mèng)幻隨手記閱讀 519評(píng)論 0 1

友情鏈接更多精彩內(nèi)容