swift UIView的阴影+

UIView的阴影+

UIViewShadow.swift
extension UIView {
    func addShadow(opacity: Float = 0.4, color: UIColor = UIColor.gray, radius: CGFloat = 4, offset: CGSize = CGSize(width: 2, height: 2)){
        layer.shadowOffset = offset
        layer.shadowOpacity = opacity
        layer.shadowColor = color.cgColor
        layer.shadowRadius = radius
        layer.masksToBounds = false
    }
}

swift 可识别

可识别

Identifiable.swift
import Foundation

protocol Identifiable: class {
    static var identifier: String { get }
}

extension Identifiable {
    static var identifier: String { return String(describing: self) }
}

extension NSObject: Identifiable {
    
}

swift 可重用单元(需要NibInstantiable,可识别文件)

可重用单元(需要NibInstantiable,可识别文件)

ReusableCell.swift
import UIKit

protocol ReusableCell: Identifiable {
    
}

extension UITableViewCell: ReusableCell {
    
}

extension UICollectionViewCell: ReusableCell {
    
}

extension UITableView {
    func register(cellClass: ReusableCell.Type){
        register(cellClass, forCellReuseIdentifier: cellClass.identifier)
    }
    
    func register(cellNib: ReusableCell.Type){
        register(UINib(nibName: cellNib.identifier, bundle: nil), forCellReuseIdentifier: cellNib.identifier)
    }
    
    func dequeueCell<T: ReusableCell>(cellClass: T.Type, for indexPath: IndexPath) -> T {
        return dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T
    }
}


extension UICollectionView {
    func register(cellClass: ReusableCell.Type){
        register(cellClass, forCellWithReuseIdentifier: cellClass.identifier)
    }
    
    func register(cellNib: ReusableCell.Type){
        register(UINib(nibName: cellNib.identifier, bundle: nil), forCellWithReuseIdentifier: cellNib.identifier)
    }
    
    func dequeueCell<T: ReusableCell>(cellClass: T.Type, for indexPath: IndexPath) -> T {
        return dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as! T
    }
}


protocol Reloadable {
    func reloadData()
}

protocol EmptyInstantiatable {
    static func instantiate() -> Self
}

extension UIScrollView {
    @objc func reload(){
        
    }
}

extension UITableView {
    @objc override func reload() {
        self.reloadData()
    }
}

extension UICollectionView {
    @objc override func reload() {
        self.reloadData()
    }
}

swift 字体类型

字体类型

FontType.swift
import UIKit

typealias FontSize = CGFloat

struct FontType: ExpressibleByStringLiteral {
    
    static let arabicName: FontType = "NotoSansArabicUI"
    
    static let regular: FontType = "Regular"
    static let ultraLight: FontType = "UltraLight"
    static let medium: FontType = "Medium"
    static let bold: FontType = "Bold"
    static let black: FontType = "Black"
    
    fileprivate var rawValue: String
    
    init(stringLiteral value: String) {
        self.rawValue = value
    }
    
    func build(with name: String) -> String {
        return name + "-" + self.rawValue
    }
    
    func with(size: CGFloat) -> UIFont {
        return UIFont(name: build(with: FontType.arabicName.rawValue), size: size)!
    }
}

swift 存储

storage
//in dataModel swiftfile
struct CompanyPropertyKey {
    static let year = "year"
    static let company = "company"
    static let event = "event"
}

class CompanyModel: NSObject, NSCoding {
    var year: String
    var company: String
    var event: String
    
    //读的时候的init
    init(year: String, company: String, event: String) {
        self.year = year
        self.company = company
        self.event = event
    }
    //取的时候的init,有的参数是读的时候没有,但取的时候就有了,需要多写一个init为读的时候服务
    init(content: String, notes: String?, isCompleted: Bool, priority: Priority) {
        self.content = content
        self.notes = notes
        self.isCompleted = isCompleted
        self.priority = priority
    }
//encode
    func encode(with aCoder: NSCoder) {
        aCoder.encode(year, forKey: CompanyPropertyKey.year)
        aCoder.encode(company, forKey: CompanyPropertyKey.company)
        aCoder.encode(event, forKey: CompanyPropertyKey.event)
    }
//decode
    required convenience init?(coder aDecoder: NSCoder) {
        guard let year = aDecoder.decodeObject(forKey: CompanyPropertyKey.year) as? String,
            let company = aDecoder.decodeObject(forKey: CompanyPropertyKey.company) as? String,
            let event = aDecoder.decodeObject(forKey: CompanyPropertyKey.event) as? String else {
                fatalError("cann't decode")
        }

        self.init(year: year, company: company, event: event)
    }
}

//create storage swiftfile
//
//  CompanyStorage.swift
//  CompaniesTimeline
//
//  Created by Jingwei Huang on 4/29/19.
//  Copyright © 2019 Feng Guo. All rights reserved.
//

import Foundation

class CompanyStorage {

    static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
    static let ArchiveURL = DocumentsDirectory.appendingPathComponent("companies")

    static func save(companies: [CompanyModel]) {
        do {
            let writeData = try NSKeyedArchiver.archivedData(withRootObject: companies, requiringSecureCoding: false)
            try writeData.write(to: CompanyStorage.ArchiveURL)
        } catch _ {
            print("failed to save")
        }
    }

    static func retrieve() -> [CompanyModel] {
        guard  let data = try? Data(contentsOf: CompanyStorage.ArchiveURL, options: []) else {
            print("No data found at location")
            return []
        }

        guard let companies = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [CompanyModel] else {
            print("can't decode")
            return []
        }

        return companies
    }

}


//in main class swiftfile
override func viewDidLoad() {
companies = CompanyStorage.retrieve()

for company in companies {
            companiesDic[company.year] = company
            }
            }

extension MainViewController: NewDelegate {
    func addItems(year: String, company: String, event: String) {
    CompanyStorage.save(companies: companies)
    }
}

swift UIView的+自动布局

UIView的+自动布局

UIViewAutolayout.swift
//
//  UIView+AutoLayout.swift
//  Prayer Times Reminder
//
//  Created by Hussein Al-Ryalat on 8/6/18.
//  Copyright © 2018 SketchMe. All rights reserved.
//

import UIKit

extension UIView {
    func pinToSafeArea(top: CGFloat? = 0, left: CGFloat? = 0, bottom: CGFloat? = 0, right: CGFloat? = 0){
        guard let superview = self.superview else { return }
        
        prepareForAutoLayout()
        
        var guide: UILayoutGuide
        if #available(iOS 11.0, *) {
            guide = superview.safeAreaLayoutGuide
        } else {
            guide = superview.layoutMarginsGuide
        }
        
        if let top = top {
            self.topAnchor.constraint(equalTo: guide.topAnchor, constant: top).isActive = true
        }
        
        if let bottom = bottom {
            self.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: bottom).isActive = true
        }
        
        if let left = left {
            self.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: left).isActive = true
        }
        
        if let right = right {
            self.rightAnchor.constraint(equalTo: guide.rightAnchor, constant: right).isActive = true
        }
    }
    
    func pinToSuperView(top: CGFloat? = 0, left: CGFloat? = 0, bottom: CGFloat? = 0, right: CGFloat? = 0){
        guard let superview = self.superview else { return }
        
        prepareForAutoLayout()
        
        if let top = top {
            self.topAnchor.constraint(equalTo: superview.topAnchor, constant: top).isActive = true
        }
        
        if let bottom = bottom {
            self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: bottom).isActive = true
        }
        
        if let left = left {
            self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: left).isActive = true
        }
        
        if let right = right {
            self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: right).isActive = true
        }
    }
    
    func centerInSuperView(){
        guard let superview = self.superview else { return }
        
        prepareForAutoLayout()
        
        self.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
        self.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
    }
    
    func constraint(width: CGFloat){
        prepareForAutoLayout()
        self.widthAnchor.constraint(equalToConstant: width).isActive = true
    }
    
    func constraint(height: CGFloat){
        prepareForAutoLayout()
        self.heightAnchor.constraint(equalToConstant: height).isActive = true
    }
    
    func makeWidthEqualHeight(){
        prepareForAutoLayout()
        self.widthAnchor.constraint(equalTo: self.heightAnchor).isActive = true
    }
    
    func prepareForAutoLayout(){
        self.translatesAutoresizingMaskIntoConstraints = false
    }
}

swift 的UIColor +六角

的UIColor +六角

UIColorHex.swift

extension UIColor {
    static func by(r: Int, g: Int, b: Int, a: CGFloat = 1) -> UIColor {
        let d = CGFloat(255)
        return UIColor(red: CGFloat(r) / d, green: CGFloat(g) / d, blue: CGFloat(b) / d, alpha: a)
    }
    
    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")
        
        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }
    
    convenience init(rgb: Int) {
        self.init(
            red: (rgb >> 16) & 0xFF,
            green: (rgb >> 8) & 0xFF,
            blue: rgb & 0xFF
        )
    }
}

swift 导航栏的东西

Nav bar stuff
        //color navbar
        UINavigationBar.appearance().tintColor = .navBarColor
        UINavigationBar.appearance().isTranslucent = false
        //Get rid of grey separator bottom of navbar
        UINavigationBar.appearance().shadowImage = UIImage()
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

swift CollectionViewCell的Autolayout

AutolayoutCollectionViewCell
let v = UIView(frame: .zero)

    let l1 = UILabel(frame: .zero)
        l1.translatesAutoresizingMaskIntoConstraints = false
        l1.font = .systemFont(ofSize: 27.0)
        l1.text = "asdlas"

    v.addSubview(l1)
    NSLayoutConstraint.activate([
      l1.topAnchor.constraint(equalTo: v.topAnchor),
      l1.leadingAnchor.constraint(equalTo: v.leadingAnchor),
    ])
    l1.setContentHuggingPriority(.required, for: .vertical)
    l1.setContentCompressionResistancePriority(.required, for: .vertical)

    let trailing = l1.trailingAnchor.constraint(equalTo: v.trailingAnchor)
        trailing.priority = .defaultHigh
    NSLayoutConstraint.activate([
      trailing
    ])

    let l2 = UILabel(frame: .zero)
        l2.translatesAutoresizingMaskIntoConstraints = false
        l2.font = .systemFont(ofSize: 17.0)
        l2.text = ""

    v.addSubview(l2)
    NSLayoutConstraint.activate([
      l2.topAnchor.constraint(equalTo: l1.bottomAnchor),
      l2.leadingAnchor.constraint(equalTo: v.leadingAnchor),
    ])
    l2.setContentHuggingPriority(.required, for: .vertical)
    l2.setContentCompressionResistancePriority(.required, for: .vertical)

    let trailing_ = l2.trailingAnchor.constraint(equalTo: v.trailingAnchor)
        trailing_.priority = .defaultHigh
    let bottom = l2.bottomAnchor.constraint(equalTo: v.bottomAnchor)
        bottom.priority = .defaultHigh
    NSLayoutConstraint.activate([
      trailing_,
      bottom
    ])


    let s = v.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

    view.addSubview(v)
    v.frame.size = s
    v.center = view.center
    v.layer.borderColor = UIColor.red.cgColor
    v.layer.borderWidth = 1.0
    
    
    //---------------------------

    func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes
  {
    let layoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)

    let fittingSize = UIView.layoutFittingCompressedSize

    layoutAttributes.frame.size = systemLayoutSizeFitting(
      fittingSize,
      withHorizontalFittingPriority: .fittingSizeLevel,
      verticalFittingPriority: .fittingSizeLevel
    )

    return layoutAttributes
  }

swift 识别码

https://www.swiftbysundell.com/posts/type-safe-identifiers-in-swift <br/> <br/>在“识别Swift中的对象”中,我们看了如何使用内置的方法识别对象在ObjectIdentifier类型中 - 本周,我们将为值构建类似的标识符类型,类型安全程度越来越高。

Identifier

struct Identifier: Hashable {
    let string: String
}

extension Identifier: ExpressibleByStringLiteral {
    init(stringLiteral value: String) {
        string = value
    }
}

extension Identifier: CustomStringConvertible {
    var description: String { return string }
}

/*
Encode&Decode the string like this:
{
    "id": {
        "string": "49-12-90-21"
    },
    "name": "John"
}
*/
extension Identifier: Codable {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        string = try container.decode(String.self)
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(string)
    }
}