swift UIImageView色彩

Tint color
extension UIImageView {
  func setImageColor(color: UIColor) {
    let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
    self.image = templateImage
    self.tintColor = color
  }
}

swift Tint UIImage

UIimage Tint color
extension UIImage {
    
    func maskWithColor(color: UIColor) -> UIImage? {
        let maskImage = cgImage!
        
        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)
        
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
        
        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)
        
        if let cgImage = context.makeImage() {
            let coloredImage = UIImage(cgImage: cgImage)
            return coloredImage
        } else {
            return nil
        }
    }
    
}

swift 乐透快速选择斯威夫特

QuickPick.swift
var ticket = [Int]()
var grabBag = Array(1...59)

for _ in 1...6 {
    let pick = grabBag.randomElement()!
    grabBag.remove(at: grabBag.firstIndex(of: pick)!)
    ticket.append(pick)
}

ticket.sort()

for n in ticket {
    print(n)
}

swift SCMainButton.swift

SCMainButton.swift
//
//  SCMainButton.swift
//  Not in a project :)
//
//  Created by Hussein AlRyalat on 5/20/19.
//  Copyright © 2019 SketchMe. All rights reserved.
//

import UIKit

@IBDesignable class SCMainButton: UIButton {
    
    fileprivate lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = tintColor
        return view
    }()
    
    
    // in case you need to change it for later
    var lineHeight: CGFloat = 2 {
        didSet {
            setNeedsLayout()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    fileprivate func setup(){
        
        // add additional space
        contentEdgeInsets = UIEdgeInsets(top: 3, left: 8, bottom: 8, right: 8)
        
        // customize the font
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        setTitleColor(.black, for: .normal)
        
        
        addSubview(lineView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        lineView.frame = CGRect(x: contentEdgeInsets.left, y: bounds.height - lineHeight, width: bounds.width - (contentEdgeInsets.right + contentEdgeInsets.left), height: lineHeight)
        lineView.frame.size.height = lineHeight
    }
    
    override func tintColorDidChange() {
        super.tintColorDidChange()
        lineView.backgroundColor = tintColor
    }
}

swift Swift Playgrounds模拟时钟示例。

Swift Playgrounds模拟时钟示例。

clock.swift
import SpriteKit
import PlaygroundSupport

class Scene: SKScene {
    var hands: [String: SKShapeNode] = [:]
    
    override func didMove(to view: SKView) {
        let center = CGPoint(x: frame.midX, y: frame.midY)
        let radius = CGFloat(450)
        let face = SKShapeNode(circleOfRadius: radius)
        face.position = center
        face.lineWidth = 10
        face.strokeColor = #colorLiteral(red: 0.8039215803146362, green: 0.8039215803146362, blue: 0.8039215803146362, alpha: 1.0)
        face.fillColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        addChild(face)
        for i in 1 ... 12 {
            let label = SKLabelNode()
            label.text = String(i)
            label.fontSize = 100
            label.fontColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
            let a = 2 * CGFloat.pi * CGFloat(i) / CGFloat(12)
            let b = CGFloat(380)
            let c = label.frame.height / 2
            let x = sin(a) * b
            let y = cos(a) * b - c
            label.position = CGPoint(x: x, y: y)
            face.addChild(label)
        }
        let attrs: [(String, CGFloat, CGFloat, UIColor)] = [
            ("m", 350, 8, #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)),
            ("h", 280, 12, #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)),
            ("s", 350, 4, #colorLiteral(red: 0.8078431487083435, green: 0.027450980618596077, blue: 0.3333333432674408, alpha: 1.0))
        ]
        for (name, length, width, color) in attrs {
            let p = CGMutablePath()
            p.move(to: CGPoint(x: 0, y: length))
            p.addLine(to: CGPoint(x: 0, y: 0))
            let s = SKShapeNode(path: p)
            s.lineWidth = width
            s.strokeColor = color
            s.lineCap = .round
            hands[name] = s
            face.addChild(s)
        }
    }
    
    override func update(_ currentTime: TimeInterval) {
        let now = Date()
        let cal = Calendar.current
        let hh = CGFloat(cal.component(.hour, from: now))
        let mm = CGFloat(cal.component(.minute, from: now))
        let ss = CGFloat(cal.component(.second, from: now))
        
        let tick = -2 * CGFloat.pi / 60
        let s = tick * ss
        let m = tick * mm
        
        let tock = -2 * CGFloat.pi / 12
        let h = tock * (hh + mm / 60)
        
        hands["s"]?.zRotation = s
        hands["m"]?.zRotation = m
        hands["h"]?.zRotation = h
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        let r = CGRect(x: 0, y: 0, width: 1000, height: 1000)
        let s = Scene(size: r.size)
        s.scaleMode = .aspectFit
        let v = SKView(frame: r)
        v.showsDrawCount = true
        v.showsNodeCount = true
        v.showsFPS = true
        v.presentScene(s)
        view = v
    }
}

PlaygroundPage.current.liveView = ViewController()
PlaygroundPage.current.wantsFullScreenLiveView = true




swift 估计字符串的高度和宽度

Estimate Height and width for strings
extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        
        return ceil(boundingBox.height)
}

    func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        
        return ceil(boundingBox.width)
    }
}

swift NibInstantiatable

NibInstantiatable.swift
import UIKit

protocol NibInstantiatable {
    
    // returns the nib
    static func nib() -> UINib
    
    // creates an object from nib
    static func loadFromNib() -> Self?
}

extension NibInstantiatable where Self: UIView {
    static func loadFromNib() -> Self? {
        return Bundle.main.loadNibNamed(identifier, owner: nil, options: nil)?.first as? Self
    }
}

extension UIView: NibInstantiatable {
    static func nib() -> UINib {
        return UINib(nibName: identifier, bundle: nil)
    }
}

swift RoundedButton

RoundedButton

RoundedButton.swift
import UIKit

class RoundedButton: UIButton {
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.bounds.height / 2
    }
}

swift CardView

CardView

CardView.swift
import UIKit

@IBDesignable class CardView: UIView {    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    func setup(){
        backgroundColor = .white
        addShadow()
        layer.cornerRadius = 6
    }
}

swift 的UIViewController +顶

的UIViewController +顶

UIViewControllerTop.swift
extension UIViewController {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}