美文网首页
日常小控件

日常小控件

作者: ngugg | 来源:发表于2018-12-10 10:55 被阅读2次

Date

extension Date {
// MARK: 时间戳转Date字符串
/// 获取系统当前时间的时间戳(毫秒)
static var timestamp: Int { // 比如: 1542699526000
return Int(Date().timeIntervalSince1970 * 1000)
}

/// 系统当前给定时间时间戳和指定时间戳之间的差值,单位秒
///
/// - Parameter timestamp: 需要做对比的时间戳
/// - Returns: 当前时间戳和给定时间戳之间的差值
static func timeInterverNow(and timestamp: Int) -> Int { // 单位秒
   return (Date.timestamp - timestamp) / 1000
}

/// 将时间戳转换为Date类型
///
/// - Parameter timestamp: 时间戳
/// - Returns: Date
static func convert(from timestamp: Int) -> Date {
    let timeInterval = TimeInterval(timestamp / 1000)
    let date = Date(timeIntervalSince1970: timeInterval)
    return date
}

/// 将Date数据转为时,分类型的字符串格式: hh:mm
var tohm: String {
    return dateFormat(style: "HH:mm")
}

/// 将Date数据转为月,日类型的字符串格式: MM月dd日
var tomd: String {
    return dateFormat(style: "MM月dd日")
}

/// 将Date数据转为年月日,时分秒类型的字符串: yyyy-MM-dd hh:mm:ss
var toymdhms: String {
    return dateFormat(style: "yyyy-MM-dd HH:mm:ss")
}

/// 将Date数据转为年月日,时分类型的字符串: yyyy-MM-dd hh:mm
var toymdhm: String {
    return dateFormat(style: "yyyy-MM-dd HH:mm")
}

/// 将Date数据转为年月日类型的字符串: yyyy-MM-dd
var toymd: String {
    return dateFormat(style: "yyyy-MM-dd")
}

/// 将Date转换为指定日期格式的字符串
///
/// - Parameter style: 日期字符串的指定样式
/// - Returns: 日期字符串
func dateFormat(style: String) -> String{
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = style
    let time = dateformatter.string(from: self)
    return time
}

// MARK: Date字符串转时间戳
/// 将年月日类型的date字符串转换为时间戳
///
/// - Parameter date: 日期字符串
/// - Returns: 时间戳
static func timestamp(ymd date: String) -> Int {
return Date.dateFormat(style: "yyyy-MM-dd", date: date)
}

/// 将年月日, 时分秒类型的Date字符串转换为时间戳
///
/// - Parameter date: 日期字符串
/// - Returns: 时间戳
static func timestamp(ymdhms date: String) -> Int {
    return Date.dateFormat(style: "yyyy-MM-dd HH:mm:ss", date: date)
}

/// 将年月日, 时分类型的Date字符串转换为时间戳
///
/// - Parameter date: 日期字符串
/// - Returns: 时间戳
static func timestamp(ymdhm date: String) -> Int {
    return Date.dateFormat(style: "yyyy-MM-dd HH:mm", date: date)
}

/// 根据指定样式将Date字符串转换为时间戳
///
/// - Parameters:
///   - style: 日期字符串的指定样式
///   - date: 日期字符串
/// - Returns: 时间戳
static func dateFormat(style: String, date: String) -> Int {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = style
    let timestamp = Int((dateFormatter.date(from: date)?.timeIntervalSince1970)!) * 1000
    return timestamp
}


/// 根据日期获取周几,比如周一
///
/// - Parameter today: 日期
/// - Returns: ""

// func getDayOfWeek(_ today:String) -> String? {
// let formatter = DateFormatter()
// formatter.dateFormat = "yyyy-MM-dd"
// guard let todayDate = formatter.date(from: today) else { return nil }
// let myCalendar = Calendar(identifier: .gregorian)
//
// let weekDay = myCalendar.component(.weekday, from: todayDate)
// return weekDays[weekDay - 1]
// }
// let weekDays = ["周日","周一","周二","周三","周四","周五","周六"]

/// 将Date转换为weekday ["周日","周一","周二","周三","周四","周五","周六"]
///
/// - Parameter date: 日期
var week: Int {
    let calendar = Calendar(identifier: .gregorian)
    return calendar.component(.weekday, from: self)
}

}

Int

extension Int {

/*
  1.小于5分钟的显示为刚刚 5 * 60s = 300s
  2.大于5分钟且小于一个小时,显示为具体多少分钟前 60 * 60s = 3600s , 比如15分钟前
  3.大于一个小时且小于24小时,显示为具体多少时间 24 * 60 比如: 15:30
  4.大于一天的显示具体日期 比如: 5月10日
*/
/// 将给定时间戳转换为具体的要求格式
var convertToDate: String {
    let timeInterval = Date.timeInterverNow(and: self) // 单位秒
    if timeInterval < 300 {
        return "刚刚"
    } else if timeInterval < 3600 {
        return "\(Int(timeInterval / 60))分钟前"
    } else if timeInterval < 86400 {
        return Date.convert(from: self).tohm
    } else {
        return Date.convert(from: self).tomd
    }
}
/// 将时间戳转为年月日,时分秒类型的字符串: yyyy-MM-dd hh:mm:ss
var toymdhms: String {
    return Date.convert(from: self).toymdhms
}

/// 将时间戳转为年月日,时分类型的字符串: yyyy-MM-dd hh:mm
var toymdhm: String {
    return Date.convert(from: self).toymdhm
}

/// 将时间戳转为年月日 类型的字符串: yyyy-MM-dd
var toymd: String {
    return Date.convert(from: self).toymd
}

/// 将时间戳转为年月日 全天类型的字符串: yyyy-MM-dd 全天
var toymdAllDay: String {
    return Date.convert(from: self).toymd + " 全天"
}

/// 日历表示中,第一天是周日,所以先减去一
var day: String {
    let weekDays = ["周日","周一","周二","周三","周四","周五","周六"]
    return weekDays[self - 1]
}

/// 今天是周几
var whichDay: String {
   return Date.convert(from: self).week.day
}

/// 将数字转为字符串
var toString: String {
    return String(self)
}

// var themeTime: String {
// let ss = toymdhms
// let weak = whichDay
//
// }
}

Array

extension Array where Element == Int {

/// 将Element为Int的数组转换为一个字符串
var toString: String {
    return self.map { String($0) }.joined(separator: ",")
}

}
extension Array where Element == String {

/// 将Element为String的数组转换为一个字符串
var toString: String {
    return self.joined(separator: ",")
}

}

string

// MARK: - Helpers
extension String {
var urlEscaped: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}

var utf8Encoded: Data {
    return data(using: .utf8)!
}

/// 将yyyy-MM-dd类型的字符串转换为时间戳
var timestamp_ymd: Int {
    return Date.timestamp(ymd: self)
}

/// 将yyyy-MM-dd hh:mm:ss类型的字符串转换为时间戳
var timestamp_ymdhms: Int {
    return Date.timestamp(ymdhms: self)
}

/// 将yyyy-MM-dd hh:mm类型的字符串转换为时间戳
var timestamp_ymdhm: Int {
    return Date.timestamp(ymdhm: self)
}
/// 将字符串转为数字
var toInt: Int {
    guard self != "" else {
        fatalError("不能转换空字符串")
    }
    return Int(self)!
}

}

extension String {
func contains(find: String) -> Bool{
return self.range(of: find) != nil
}
}

UIViewController

extension UIViewController {

/// push 一个 UIViewController或者其子类
@discardableResult
func pushFrom(_ rootViewController: UIViewController) -> Self {
    rootViewController.navigationController?.pushViewController(self, animated: true)
    return self
}

/// 将 子控制器vc的view 显示在 keyWindow 上面

// func show(_ vc: UIViewController, in parent: UIViewController) {
// vc.view.frame = CGRect(x: 0, y: 0, width: djScreenWidth, height: djScreenHeight)
// let window = UIApplication.shared.keyWindow
// window?.addSubview(vc.view)
// parent.addChild(vc)
// }

/// 将视图展示在 keyWindow 上
///
/// - Parameter parent: 父视图控制器
func show(in parent: UIViewController) {
    self.view.frame = CGRect(x: 0, y: 0, width: djScreenWidth, height: djScreenHeight)
    let window = UIApplication.shared.keyWindow
    window?.addSubview(self.view)
    parent.addChild(self)
}

}

UITextView

extension UITextView {

/// 初始化一个textView,使用 textColor, font
convenience init (textColor: UIColor, font: CGFloat) {
    self.init()
    self.textColor = textColor
    self.font = UIFont.systemFont(ofSize: font)
}
/// 初始化一个textView,使用 placeholder, textColor, font
convenience init (_ placeholder: String, textColor: UIColor, font: CGFloat) {
    self.init()
    self.textColor = textColor
    self.font = UIFont.systemFont(ofSize: font)
    let label = UILabel(text: placeholder, textColor: cmGray99, font: 13)
    label.numberOfLines = 0
    label.sizeToFit()
    self.addSubview(label)
    setValue(label, forKey: "_placeholderLabel")
}

}

UITextField

extension UITextField {
/// 初始化一个Label,with text, textColor, font
convenience init (_ placeholder: String, _ placeholderColor: UIColor, font: CGFloat = 0) {
self.init()
self.placeholder = placeholder
self.font = UIFont.systemFont(ofSize: font)
self.textColor = placeholderColor
}

/// 初始化一个属性UITextField,with text, textColor, font
convenience init (_ attrPlaceholder: String, _ placeholderColor: UIColor, textColor: UIColor, font: CGFloat = 0) {
    self.init()
    self.attributedPlaceholder = NSMutableAttributedString(string: attrPlaceholder, attributes: [NSAttributedString.Key.foregroundColor : placeholderColor])
    self.font = UIFont.systemFont(ofSize: font)
    self.textColor = textColor
}

}

UIlabel

extension UILabel {

/// 初始化一个Label,with text, textColor, font
convenience init (text: String, textColor: UIColor, font: CGFloat = 0) {
    self.init()
    self.text = text
    self.font = UIFont.systemFont(ofSize: font)
    self.textColor = textColor
}

func align(style: NSTextAlignment) -> Self {
    textAlignment = style
    return self
}
func font(size: UIFont) -> Self {
    font = size
    return self
}

}

UIImageView

extension UIImageView {

/// 允许交互
var allowInteraction: UIImageView {
    isUserInteractionEnabled = true
    return self
}   

}

UIButton

extension UIButton {

/// 初始化一个UIbutton,使用 title, titleColor, fontSize
convenience init(_ title: String, titleColor: UIColor, fontSize: CGFloat) {
    self.init(frame: .zero)
    setTitle(title, for: .normal)
    titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
    setTitleColor(titleColor, for: .normal)
}

/// 添加点击响应事件
@discardableResult
func add(_ target: Any?, action: Selector) -> Self {
    addTarget(target, action: action, for: .touchUpInside)
    return self
}

/// 设置选中时的颜色
@discardableResult
func selected(color: UIColor) -> Self {
    setTitleColor(color, for: .selected)
    return self
}

/// 设置tag值
@discardableResult
func tag(_ value: Int) -> Self {
    tag = value
    return self
}

/// 设置普通状态下的标题
@discardableResult
func normalTitle(_ value: String) -> Self {
    setTitle(value, for: .normal)
    return self
}

/// 设置选中状态下的标题
@discardableResult
func selectedTitle(_ value: String) -> Self {
    setTitle(value, for: .selected)
    return self
}

/// 设置普通状态下的背景图片
@discardableResult
func normalBackgroundImage(_ value: UIImage) -> Self {
    setBackgroundImage(value, for: .normal)
    return self
}
/// 设置普通状态下的背景图片 使用 String
@discardableResult
func normalBackgroundImage(_ value: String) -> Self {
    setBackgroundImage(dj_image(value), for: .normal)
    return self
}

/// 设置选中状态下的背景图片
@discardableResult
func selectedBackgroundImage(_ value: UIImage) -> Self {
    setBackgroundImage(value, for: .selected)
    return self
}

/// 设置文本颜色 使用 String
@discardableResult
func textColor(_ value: String) -> Self {
    setTitleColor(dj_hexColor(value), for: .normal)
    return self
}

}

UIView

extension UIView {

/// 设置初始背景色

/// - Parameter backgroundColor: UIColor
convenience init(backgroundColor: UIColor) {
    self.init(frame: .zero)
    self.backgroundColor = backgroundColor
}


/// 创建一个背景色为ededed的view
static var ededed: UIView {
    return UIView(backgroundColor: cmEDEDED)
}

/// 设置圆角半径
@discardableResult
func corner(radius: CGFloat) -> Self {
    layer.cornerRadius = radius
    layer.masksToBounds = true
    return self
}

/// 设置背景色
func background(color: UIColor) -> Self {
    backgroundColor = color
    return self
}

/// 将view添加到父视图
@discardableResult
func addTo(_ superView: UIView) -> Self {
    superView.addSubview(self)
    return self
}

/// 将view添加到父视图
func alpha(_ value: CGFloat) -> Self {
    alpha = value
    return self
}

}

UITableView

typealias TableViewProtocol = UITableViewDelegate & UITableViewDataSource

extension UITableView {
/// 初始化一个UITableView
///
/// - Parameters:
/// - vc: 代理和数据源对象
convenience init(_ vc: TableViewProtocol, style: UITableView.Style = .plain) {
self.init(frame: .zero, style: style)
delegate = vc
dataSource = vc
separatorStyle = .none
backgroundColor = .white
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
}

/// 初始化一个UITableView,指定样式类型,并注册相关cell
///
/// - Parameters:
///   - vc: 代理和数据源对象
///   - cellType: 要注册的cell
convenience init(_ vc: TableViewProtocol, style: UITableView.Style = .plain, cellTypes: [UITableViewCell.Type], reuseID: [String]) {
    self.init(vc, style: style)
    for (index, item) in cellTypes.enumerated() {
        register(item, forCellReuseIdentifier: reuseID[index])
    }
}


/// 设置行高度
func rowHeight(_ height: CGFloat) -> Self {
    rowHeight = height
    return self
}


/// 在只有的情况下,根据行号返回相关cell
func getCell(row: Int) -> UITableViewCell? {
    let indexPath = IndexPath(row: row, section: 0)
    return cellForRow(at: indexPath)
}

}

UIImage

extension UIImage {

/// 用于设置cell的背景图片拉伸
static var cm_shadow: UIImage? {
    let image = UIImage(named: "")
    let insets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
    return image?.resizableImage(withCapInsets: insets, resizingMode: UIImage.ResizingMode.stretch)
}

static var cm_dotLine: UIImage? {
    let image = UIImage(named: "")
    return image?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: UIImage.ResizingMode.tile)
}

}

extension UIAlertAction {

static var cm_titleTextColor = "titleTextColor"

static var cancel: UIAlertAction {
    return UIAlertAction(title:"取消", style: .cancel, handler:nil)
}

@discardableResult
func titleColor(_ color: UIColor) -> UIAlertAction {
    setValue(color, forKey: UIAlertAction.cm_titleTextColor)
    return self
}

static func resetCancelActionStyle(_ action: UIAlertAction) {

    let attributedText = NSMutableAttributedString(string: "取消")

    let range = NSRange(location: 0, length: 4)
    attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: , range: range)
    attributedText.addAttribute(NSAttributedString.Key.font, value: , range: range)

    guard let label = (action.value(forKey: "__representer")as? NSObject)?.value(forKey: "label") as? UILabel else { return }
    label.attributedText = attributedText
}

}

UIAlertController

extension UIAlertController {

}

typealias ActionClourse = ((UIAlertAction) -> Void)?
extension UIViewController {

/// 初始化一个ActionSheet, 使用两个不同的方式
///
/// - Parameters:
///   - topTitle: 第一功能标题    例如: 拍照
///   - topAction: 第一功能
///   - secondTitle: 第一功能标题  例如: 从手机相册选择
///   - action2: 第二功能
func popActionSheet(_ topTitle: String, _ topAction: ActionClourse, _ secondTitle: String, _ secondAction: ActionClourse) {
    
    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    let action1 = UIAlertAction(title: topTitle, style: .default, handler: topAction)
    
    let action2 = UIAlertAction(title: secondTitle, style: .default, handler: secondAction)
  
    let action3 = UIAlertAction(title: "取消", style: .cancel) { (action:UIAlertAction) in
        print("You've pressed cancel");
    }
    
    [action1, action2, action3].forEach {
        alertController.addAction($0)
        $0.titleColor(cmBlack33)
    }
    present(alertController, animated: true, completion: nil)
    
}

/// 初始化一个ActionSheet, 删除和取消两个功能
func popActiondelete( _ action: ActionClourse) {
    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
    let action1 = UIAlertAction(title: "删除", style: .default, handler: action)
    
    let action2 = UIAlertAction(title: "取消", style: .cancel) { (action:UIAlertAction) in
        print("You've pressed cancel");
    }
    
    [action1, action2].forEach {
        alertController.addAction($0)
        $0.titleColor(cmBlack33)
    }
    present(alertController, animated: true, completion: nil)
}

/// 初始化一个ActionSheet, 使用两个不同的方式
///
/// - Parameters:
///   - topTitle: 第一功能标题    例如: 拍照
///   - topAction: 第一功能
///   - secondTitle: 第一功能标题  例如: 从手机相册选择
///   - action2: 第二功能
func popActionSheetFourOptions(_ topTitle: String, _ topAction: ActionClourse, _ secondTitle: String, _ secondAction: ActionClourse, _ thirdTitle: String, _ thirdAction: ActionClourse) {
    
    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
    let action1 = UIAlertAction(title: topTitle, style: .default, handler: topAction)
    
    let action2 = UIAlertAction(title: secondTitle, style: .default, handler: secondAction)
    
    let action3 = UIAlertAction(title: thirdTitle, style: .default, handler: thirdAction)
    
    let action4 = UIAlertAction(title: "取消", style: .cancel) { (action:UIAlertAction) in
        print("You've pressed cancel");
    }
    
    [action1, action2, action3, action4].forEach {
        alertController.addAction($0)
        $0.titleColor(cmBlack33)
    }
    present(alertController, animated: true, completion: nil)
}

/// 确认提示框
///
/// - Parameters:
///   - title: 提醒框标题
///   - message: 提示内容
///   - buttonTitle: 确定按钮标题
///   - action: 确定回调
func popConfirmAlert(title: String = "", message: String = "", buttonTitle: String, action: ActionClourse) {
    
    let alertController = UIAlertController(title: title,
                                            message: message,
                                            preferredStyle: .alert)
    
    let cancelAction = UIAlertAction(title: "取消", style: .default) { (action:UIAlertAction) in
        print("You've pressed cancel");
    }
    cancelAction.titleColor(cmGray99)
    
    let settingsAction = UIAlertAction(title: buttonTitle, style: .default, handler: action)
    settingsAction.titleColor(cmThemeColor)
    
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)
    
    present(alertController, animated: true, completion: nil)
}

相关文章

  • 日常小控件

    Date extension Date {// MARK: 时间戳转Date字符串/// 获取系统当前时间的时间戳...

  • Android超级好用的CheckView

    前言 多选和单选是日常开发经常用的控件,android系统原生的控件样式(RadioButton 、CheckBo...

  • 2018-06-09

    自定义控件的基本原理 在日常的android开发中会经常和控件打交道,有时android提供的控件未能满足业务需求...

  • Android TextView动态设置

    背景 在日常开发中我们经常会遇到需要展示多个TextView控件。因为TextView控件个数的不确定,下面就需要...

  • iOS自定义控件开发梳理

    在日常iOS开发中,系统提供的控件常常无法满足业务功能,这个时候需要我们实现一些自定义控件。自定义控件能让我们完全...

  • iOS 自定义控件 自定义进度条

    在日常iOS开发中,系统提供的控件常常无法满足业务功能,这个时候需要我们实现一些自定义控件。自定义控件能让我们完全...

  • 日常控件交互记录

    1、弹出框,“确定”、“取消”位置争议: “确定”应该放在左边、还是“取消”应该放在左边。 windows电脑,...

  • 简单实现UIlabel可复制功能

    在我们日常的开发中经常会遇到一些小需求,比如需要长按控件来拷贝控件中得内容.我们知道在iOS中有三个控件自身是支持...

  • android随笔之自定义View基本原理

    前言:在日常的Android开发中会经常和控件打交道,有时Android提供的控件未必能满足业务的需求,这个时候就...

  • 小程序即时通讯

    小程序即时通讯——文本、语音输入控件(一)集成 小程序即时通讯——文本、语音输入控件(一)集成聊天输入组件控件样式...

网友评论

      本文标题:日常小控件

      本文链接:https://www.haomeiwen.com/subject/yfhrhqtx.html