当前位置:网站首页>Swift common extension classes and simple encapsulation
Swift common extension classes and simple encapsulation
2022-07-30 10:52:00 【chenzoff】
- 将16base color conversion toRGB
/**
* UIColor的扩展类 将16base color conversion toRGB
* @param hexString 16进制颜色字符串
*/
extension UIColor{
convenience init(hexString: String) {
let scanner:Scanner = Scanner(string:hexString)
var valueRGB:UInt32 = 0
if scanner.scanHexInt32(&valueRGB) == false {
self.init(red: 0,green: 0,blue: 0,alpha: 0)
}else{
self.init(
red:CGFloat((valueRGB & 0xFF0000)>>16)/255.0,
green:CGFloat((valueRGB & 0x00FF00)>>8)/255.0,
blue:CGFloat(valueRGB & 0x0000FF)/255.0,
alpha:CGFloat(1.0)
)
}
}
}
- 生成随机颜色
/**
* 扩展UIColor 生成随机颜色
*/
extension UIColor {
class var randomColor: UIColor {
get {
let red = CGFloat(arc4random()%256)/255.0
let green = CGFloat(arc4random()%256)/255.0
let blue = CGFloat(arc4random()%256)/255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
}
- 获取当前的viewController
/**
* UIViewController 的扩展类 获取当前的ViewController
* 使用时只需let nowVC = UIViewController.currentViewController()
*/
extension UIViewController {
class func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return currentViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
return currentViewController(base: tab.selectedViewController)
}
if let presented = base?.presentedViewController {
return currentViewController(base: presented)
}
return base
}
}
- Add one to the gesturetag属性
/**
* UITapGestureRecognizer 的扩展类 Add one to the gesturetag属性
*/
private var tagKey: Int?
extension UITapGestureRecognizer {
var gestureTag: Int? {
get {
return objc_getAssociatedObject(self, &tagKey) as? Int
}
set(newValue) {
objc_setAssociatedObject(self, &tagKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
}
}
- String的MD5加密
/**
* String 的扩展类
* MD5 加密
*/
extension String {
func getMD5() -> String {
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize(count: digestLen)
return String(hash)
}
}
- swiftSimple encapsulation of network requestsAlamofire
//********** Custom network request wrapper **********
import UIKit
import Alamofire
let RootUrl = "Here is the project's domain name"
//网络类型枚举:get post
enum MethodType {
case get, post
}
//Network request type address enumeration
enum APIUrl: String {
//登录
case login = "***"
//注册
case regist = "***"
//Others are customized according to their own project interface documentation
}
class LTNetWorkTool {
class func requestData(_ type : MethodType, URL : String, parameters : [String : Any], callBack : @escaping (_ result : Any) -> ()) -> Void {
//1. Get the network request type and network request address
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
let url = RootUrl + URL
//2. 网络请求
let request = Alamofire.request(url, method: method, parameters: parameters, encoding: URLEncoding.default, headers: nil)
request.responseJSON { (response) in
//3. 获取结果
guard let result = response.result.value else {
print("request error for : " + URL)
print(response.result.error!)
return
}
//4. Call back the result
callBack(result)
}
}
}
作者:Pick up pick up pick up pick up pick up pick up
链接:https://www.jianshu.com/p/86be9defb4f5
来源:简书
著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.
边栏推荐
- [100 Solidity Skills] 1. Contract reentrancy attack
- [Deep Learning] (Problem Record)
- Linear Regression - Small Batch Stochastic Gradient Descent - Js array operating mobile for encapsulation
- Re20:读论文的先例:普通法的信息理论分析
- log4js入门
- Matplotlib--plot markers
- Unity 锁定相机第二弹
- (C language) file operation
- idea2021+Activiti [the most complete note one (basic use)]
- MFCC to audio, the effect should not be too funny >V
猜你喜欢
FPGA刷题——计数器(简易秒表、可置位计数器、加减计数器)
TestNg整合Retry代码
spark udf accepts and handles null values.
Neural Network Study Notes 4 - Autoencoder (including sparse, stacked) (updated)
360发布面向未来的EDR,全方位守护政企用户终端安全
Re17: Read the paper Challenges for Information Extraction from Dialogue in Criminal Law
Do you really understand the 5 basic data structures of Redis?
Unity 锁定相机第二弹
2022全球数字经济大会人工智能专场:AI安全受高度关注
第2章 常用安全工具
随机推荐
R语言怎么绘图(一个r语言完整的命令有什么)
PyQt5 - draw text on window
OC-手动引用计数内存管理
Basemap and Seaborn
jmeter接口压力测试-(二)
WebAPI 复习
JSP 语法简介说明
Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解
【HMS core】【Analytics Kit】【FAQ】如何解决华为分析付费分析中付款金额显示为0的问题?
SST-Calib:结合语义和VO进行时空同步校准的lidar-visual外参标定方法(ITSC 2022)
数据库事务,JDBC操作和数据类型
TestNg整合Retry代码
Selected System Design | Design of CAN Bus Controller Based on FPGA (with Code)
Classes and Objects - 6 Default Member Functions
Drag and drop events, dataTransfer, getBoundingClientRect
mysql分页查询倒序_【Mysql笔记】MySQL实现分页查询[通俗易懂]
vscode中写markdown格式笔记的配置过程和相关语法
Easy gene: human tRNA gene loci showed age-related high DNA methylation | research articles
还在用Swagger?我推荐这款零代码侵入的接口管理神器
spark udf accepts and handles null values.