Created by CyanHall.com on 11/25/2020 , Last updated: 01/08/2021.
👉  github shields Star me if it’s helpful.

1. Basic

    var sampleDict: Dictionary<String, Any> = [:]
var sampleList: [String] = []

// List Dict Keys
Array(dict.keys) 

let array = [(2, "is"), (0, "Hello"), (1, "this"), (3, "Ben")]
let sortedArray = array.sort { $0.0 < $1.0 }

print(sortedArray) // [(0, "Hello"), (1, "this"), (2, "is"), (3, "Ben")]

// Dynamic Access
@IBOutlet weak var view1: UIView!
let view1Alias = self.value(forKey: "view1") as! UIView

Double(5.5).rounded(.down) // floor: 5
Double(5.5).rounded(.up) // ceil: 6
  

2. String

    let datetimeStr = "2020-11-29 15:03:14"
let index = datetimeStr.index(datetimeStr.startIndex, offsetBy: 10)
let dateStr = String(datetimeStr[..<index])
print(dateStr) // 2020-11-29

let someString = "1, 2, 3, 4"
let substrings = someString.components(separatedBy: ", ")
substrings.joined(separator: ", ")
  

3. Dictionary

    // Check key exist
dict.keys.contains(key)
  

4. Button

    sampleBtn.setTitleColor(.balck, for: .normal)
sampleBtn.setImage(UIImage.init(named: "sample_icon"), for: .normal)
  

5. UILabel

    label.font = UIFont.systemFont(ofSize: 10)
  

6. UIBarButtonItem

    let backItem = UIBarButtonItem(image: UIImage(named: "icon_back") , style: UIBarButtonItemStyle.plain, target: self, action: #selector(clickBack))
self.navigationItem.leftBarButtonItem = backItem
let rightItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(clickSaveAction))
rightItem.setTitleTextAttributes([.foregroundColor: UIColor.red], for: .normal) // Set text color
self.navigationItem.rightBarButtonItem = rightItem

@objc func clickSaveAction() -> Void{

}
@objc func clickBack() {
    self.navigationController?.popViewController(animated: true)
}
  

7. cornerRadius

    let view = UIView()
view.clipsToBounds = true
view.layer.cornerRadius = 10
// Top right corner, Top left corner respectively
view.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
  

8. Adding shadow to top of UIView

    enum VerticalLocation: String {
    case bottom
    case top  
}

extension UIView {
    func addShadow(location: VerticalLocation, color: UIColor = .black, opacity: Float = 0.5, radius: CGFloat = 5.0) {
        switch location {
        case .bottom:
             addShadow(offset: CGSize(width: 0, height: 10), color: color, opacity: opacity, radius: radius)
        case .top:
            addShadow(offset: CGSize(width: 0, height: -10), color: color, opacity: opacity, radius: radius)
        }
    }

    func addShadow(offset: CGSize, color: UIColor = .black, opacity: Float = 0.5, radius: CGFloat = 5.0) {
        self.layer.masksToBounds = false
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOffset = offset
        self.layer.shadowOpacity = opacity
        self.layer.shadowRadius = radius
    }
}
  

9. navigationBar

    // Hide navigationBar
self.navigationController?.navigationBar.isHidden = true
  

10. Load Xib Resources

    let vc = MyViewController() //  VC with Xib Resources
vc.loadViewIfNeeded() // Load Xib Resources
  

11. Loop

    for i in 1..<7 {
  print(i)
}
// 1 2 3 4 5 6

let items = [
    "name": "Cyanhall",
    "author": "Cyanhall"
]
for item in items {
    print("(item.value): (item.key)")
}
for item in items.reversed() {
    print("(item.value): (item.key)")
}
for (index, item) in items.enumerated() {
  print("(index). (item.value): (item.key)")
}
  

12. navigationItems

    override func viewDidLoad() {
    super.viewDidLoad()
    let editImage    = UIImage(named: "edit")!
    let searchImage  = UIImage(named: "search")
    let editButton   = UIBarButtonItem(image: editImage,  style: .plain, target: self, action: #selector(didTapEditButton(sender:)))
    let searchButton = UIBarButtonItem(image: searchImage,  style: .plain, target: self, action: #selector(didTapSearchButton(sender:)))
    navigationItem.rightBarButtonItems = [editButton, searchButton]
}
@objc func didTapEditButton(sender: AnyObject){

}

@objc func didTapSearchButton(sender: AnyObject){

}
  

13. Notification

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CHforCyanhall"), object: data)

NotificationCenter.default.addObserver(
  self,
  selector: #selector(self.handllCyanhallNotification),
  name: Notification.Name("CHforCyanhall"),
  object: nil)

@objc private func handllCyanhallNotification(notification: NSNotification?){
  print(notification.object) // data
}
deinit {
  NotificationCenter.default.removeObserver(self)
}
  

14. Execute code on Main UI Thread

    DispatchQueue.global(qos: .background).async {
  // Execute code on Background Thread
}
DispatchQueue.main.async {
  // Execute code on Main UI Thread
}
  

15. ImageView load Image

    import Kingfisher

let url = URL(string: "[path]")
self.avatarImage.kf.setImage(with: url)
  

16. Pragma Mark

    // MARK: Swift

#pragma mark - Objective-C
  

17. Click Block

    // sampleCell
var sampleBlock:(()->())?
func clickSampleBlock(block:@escaping (()->())) -> Void {
    sampleBlock = block
}
// tableView
cell.clickSampleBlock{() in
    if isLike {
        print(item)
    } else {
        print(item)
    }
}
// or 
cell.sampleBlock = {
  
}
  

18. UICollectionView/UITableView inside UIScrollView

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapOnScollView))
tap.numberOfTapsRequired = 1
myScollView.addGestureRecognizer(tap)

@objc func tapOnScollView(_ sender: UITapGestureRecognizer) {
    let touchLocation = sender.location(ofTouch: 0, in: self.collectionView)
    let indexPath = self.collectionView.indexPathForItem(at: touchLocation)
    if indexPath != nil {
        // Do somthing 
    }
}
  

19. Date String Extension

    // String+Extension.swift
func FormatDateTime(formartString:String, fromFormat:String = "yyyy-MM-dd HH:mm:ss") -> String {
    if self.count == 0 {return ""}
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = fromFormat
    let date = dateFormatter.date(from: self)
    
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = formartString
    let strNowTime = timeFormatter.string(from: date! ) as String
    return strNowTime
}

func TimeToNow() -> String {
    //获取当前的时间戳
    let currentTime = Date().timeIntervalSince1970
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = dateFormatter.date(from: self)
    
    let dateStamp:TimeInterval = date!.timeIntervalSince1970
    
    let dateStr:Double = Double(dateStamp)
    //时间差
    let reduceTime : TimeInterval = currentTime - dateStr
    //时间差小于60秒
    if reduceTime < 60 {
        return "刚刚"
    }
    //时间差大于一分钟小于60分钟内
    let mins = Int(reduceTime / 60)
    if mins < 60 {
        return "(mins)分钟前"
    }
    let hours = Int(reduceTime / 3600)
    if hours < 24 {
        return "(hours)小时前"
    }
    let days = Int(reduceTime / 3600 / 24)
    if days < 30 {
        return "(days)天前"
    }
    //不满足上述条件---或者是未来日期-----直接返回日期
    return self.FormatDateTime(formartString: "yyyy年MM月dd日 HH:mm:ss")
}

// 2020-11-30 12:00:00 => 2020-11-30
let date = "2020-11-30 12:00:00"
date.FormatDateTime(formartString: "yyyy-MM-dd")
date.TimeToNow()
  


Maitained by Cyanhall.com, Copy Rights @ CC BY-NC-SA 4.0