swift UIFont +助手

font helper
import UIKit

extension UIFont {
    
    static let dashboardCardTitle = UIFont.SFProSemiBold(size: 17)
    static let dashboardCardSubtitle = UIFont.SFProRegular(size: 15)
 // etc with other constants
    
    static public func SFProRegular(size: CGFloat) -> UIFont {
        guard let font = UIFont(name: "SFProDisplay-Regular", size: size) else {
            return UIFont.systemFont(ofSize: size)
        }
        return font
    }
    static public func SFProSemiBold(size: CGFloat) -> UIFont {
        guard let font = UIFont(name: "SFProDisplay-Semibold", size: size) else {
            return UIFont.boldSystemFont(ofSize: size)
            
        }
        return font
    }
    static public func SFProMedium(size: CGFloat) -> UIFont {
        guard let font = UIFont(name: "SFProDisplay-Medium", size: size) else {
            return UIFont.systemFont(ofSize: size)
        }
        return font
    }
}

swift CALayer的+帮手

CALayerHelper
import UIKit

extension CAGradientLayer {
    convenience init(colors: [CGColor]?, locations: [NSNumber]? = nil, startPoint: CGPoint = CGPoint(x: 0.5, y: 0), endPoint: CGPoint = CGPoint(x: 0.5, y: 1.0), frame: CGRect = .zero) {
        self.init()
        self.frame = frame
        self.colors = colors
        self.locations = locations
        self.startPoint = startPoint
        self.endPoint = endPoint
    }
}

//to define later on some custom layers
class OverlayLayer: CAGradientLayer {
    override func layoutSublayers() {
        super.layoutSublayers()
        self.colors = [UIColor.red.cgColor,
                       UIColor.yellow.cgColor,
                       UIColor.green.cgColor]
    }
}

swift 的UIButton +助手

Button helper
import UIKit

extension UIButton {
    static public func systemButton(title: String? = nil, image: UIImage? = nil, titleColor: UIColor? = .white, font: UIFont? = nil, target: Any? = nil, selector: Selector? = nil) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.imageView?.contentMode = .scaleAspectFit
        button.setTitleColor(titleColor, for: .normal)
        button.titleLabel?.font = font
        if let selector = selector {
            button.addTarget(target, action: selector, for: .touchUpInside)
        }
        return button
    }
}

swift UIStackView +助手(未完成)

stackview

import UIKit

extension UIStackView {
    convenience init(axis: NSLayoutConstraint.Axis? = NSLayoutConstraint.Axis.horizontal , alignment: Alignment? = .fill, distribution: Distribution? = .fill, spacing: CGFloat? = 0, arrangedSubviews: [UIView]) {
        self.init(arrangedSubviews: arrangedSubviews)
        if let axis = axis {
            self.axis = axis
        }
        if let alignment = alignment {
            self.alignment = alignment
        }
        if let distribution = distribution {
            self.distribution = distribution
        }
        if let spacing = spacing {
            self.spacing = spacing
        }
    }
    
    func addArrangedSubviews(_ views: UIView...) {
        views.forEach { addArrangedSubview($0) }
    }
    func removeAllArrangedSubviews() {
        let removedSubviews = arrangedSubviews.reduce([]) { (allSubviews, subview) -> [UIView] in
            self.removeArrangedSubview(subview)
            return allSubviews + [subview]
        }
        removedSubviews.forEach({ $0.removeFromSuperview() })
    }
}

swift 的UITextView +帮手

textviewhelper

import UIKit

extension UITextView {
    convenience init(text: String? ,font: UIFont?, color: UIColor?) {
        self.init(frame: .zero)
        self.text = text
        self.textColor = color
        self.font = font
        self.backgroundColor = .clear
        self.isEditable = false
    }
}

extension UITextField {
    convenience init(placeholder: String = "", font: UIFont? = nil, backgroundColor: UIColor
        = .clear, borderStyle: UITextField.BorderStyle = .none) {
        self.init(frame: .zero)
        self.placeholder = placeholder
        self.backgroundColor = backgroundColor
        self.borderStyle = borderStyle
        if let font = font {
            self.font = font
        }
    }
}

swift 的UILabel +帮手

UIlabel
import UIKit

extension UILabel {
    convenience init(text: String? , font: UIFont?, color: UIColor?,textAlignment: NSTextAlignment? = nil, numberOfLines: Int? = 1 ) {
        self.init(frame: .zero)
        self.text = text
        self.font = font
        self.textColor = color
        self.textAlignment = textAlignment ?? .left
        self.numberOfLines = numberOfLines ?? 1
    }
}

swift 的UIColor +助手

Uicolorhelper
import UIKit

extension UIColor {
    convenience init(redValue: CGFloat , greenValue: CGFloat , blueValue: CGFloat, alphaValue: CGFloat) {
        self.init(red: redValue/255, green: greenValue/255, blue: blueValue/255, alpha: alphaValue)
    }

    convenience init(hex : Int ) {
        let (red, green, blue) = (CGFloat((hex >> 16) & 0xFF),CGFloat((hex >> 8) & 0xFF),CGFloat(hex & 0xFF))
        self.init(redValue: red, greenValue: green, blueValue: blue, alphaValue: 1.0)
    }
    
    convenience init(hex: Int, alpha: CGFloat) {
        let (red, green, blue) = (CGFloat((hex >> 16) & 0xFF),CGFloat((hex >> 8) & 0xFF),CGFloat(hex & 0xFF))
        self.init(redValue: red, greenValue: green, blueValue: blue, alphaValue: alpha)
    }
    
}

swift 的UIImage + Helper.swift

UIImagehelper
import UIKit

extension UIImageView {
    convenience init(image: UIImage?,contentMode: UIView.ContentMode?, cornerRadius: CGFloat? = 0, userInteraction: Bool? = false) {
        self.init(frame: .zero)
        if let image = image {
            self.image = image
        }
        if let contentMode = contentMode {
            self.contentMode = contentMode
        }
        if let cornerRadius = cornerRadius {
            self.clipsToBounds = true
            self.layer.cornerRadius = cornerRadius
        }
        if let userInteraction  = userInteraction {
            self.isUserInteractionEnabled  = userInteraction
        }
    }
}

extension UIImage {
    func resizeWithCGsize(scaledToSize newSize:CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
    
    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 自定义分段控制

Custom Segmented control

import UIKit

@IBDesignable class CustomSegmentedControl: UISegmentedControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    func update(){
        let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.white ]
        setTitleTextAttributes(attributes, for: .normal)
        setTitleTextAttributes(attributes, for: .selected)
        for index in 0 ..< numberOfSegments {
            if let image = imageForSegment(at: index)?.withRenderingMode(.alwaysOriginal) {
                setImage(image, forSegmentAt: index)
            }
        }
    }

     func setupView() {
        let insets = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
        let backgroundNormal = #imageLiteral(resourceName: "SegmentedControl-Background-Normal").resizableImage(withCapInsets: insets, resizingMode: .stretch)
        let backgroundSelected = #imageLiteral(resourceName: "SegmentedControl-Background-Selected").resizableImage(withCapInsets: insets, resizingMode: .stretch)
        let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.white ]

        setBackgroundImage(backgroundNormal, for: .normal, barMetrics: .default)
        setBackgroundImage(backgroundSelected, for: .selected, barMetrics: .default)
        setDividerImage(#imageLiteral(resourceName: "SegmentedControl-Divider-NormalNormal"), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
        setDividerImage(#imageLiteral(resourceName: "SegmentedControl-Divider-SelectedNormal"), forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
        setDividerImage(#imageLiteral(resourceName: "SegmentedControl-Divider-NormalSelected"), forLeftSegmentState: .normal, rightSegmentState: .selected, barMetrics: .default)

        setTitleTextAttributes(attributes, for: .normal)
        setTitleTextAttributes(attributes, for: .selected)
        for index in 0 ..< numberOfSegments {
            if let image = imageForSegment(at: index)?.withRenderingMode(.alwaysOriginal) {
                setImage(image, forSegmentAt: index)
            }
        }
    }
}

swift 图像与文本

image with text helper
extension UIImage {
    func withText(_ text: String, color: UIColor = .white, imageAlignment: Int = 0, usingFont: UIFont? = nil) -> UIImage {
        let font = usingFont ?? UIFont.systemFont(ofSize: 14.0)
        let expectedTextSize: CGSize = (text as NSString).size(withAttributes:[ NSAttributedString.Key.foregroundColor: color , NSAttributedString.Key.font: font])

        let width: CGFloat = expectedTextSize.width + self.size.width + 5.0
        let height: CGFloat = max(expectedTextSize.height, self.size.width)
        let size: CGSize = CGSize(width: width, height: height)

        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let context = UIGraphicsGetCurrentContext()!
        context.setFillColor((UIColor.white).cgColor)

        let fontTopPosition: CGFloat = (height - expectedTextSize.height) / 2.0
        let textOrigin: CGFloat = (imageAlignment == 0) ? self.size.width + 5 : 0
        let textPoint: CGPoint = CGPoint(x: textOrigin, y: fontTopPosition)

         text.draw(at: textPoint, withAttributes: [ NSAttributedString.Key.foregroundColor: color , NSAttributedString.Key.font: font])
        let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)
        context.concatenate(flipVertical)

        let alignment: CGFloat =  (imageAlignment == 0) ? 0.0 : expectedTextSize.width + 5.0
        context.draw(self.cgImage!, in: CGRect(x: alignment, y: ((height - self.size.height) / 2.0), width: self.size.width, height: self.size.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
}