当前位置:网站首页>Swift 常用扩展类和简单封装
Swift 常用扩展类和简单封装
2022-07-30 10:28:00 【chenzoff】
- 将16进制颜色转换为RGB
/**
* UIColor的扩展类 将16进制颜色转换为RGB
* @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
}
}
- 给手势添加一个tag属性
/**
* UITapGestureRecognizer 的扩展类 给手势添加一个tag属性
*/
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)
}
}
- swift简单封装网络请求Alamofire
//********** 自定义网络请求封装 **********
import UIKit
import Alamofire
let RootUrl = "这里是项目的域名"
//网络类型枚举:get post
enum MethodType {
case get, post
}
//网络请求类型地址枚举
enum APIUrl: String {
//登录
case login = "***"
//注册
case regist = "***"
//其他根据自己项目接口文档自定义
}
class LTNetWorkTool {
class func requestData(_ type : MethodType, URL : String, parameters : [String : Any], callBack : @escaping (_ result : Any) -> ()) -> Void {
//1. 获取网络请求类型和网络请求地址
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. 将结果回调出去
callBack(result)
}
}
}
作者:拾拾拾拾拾拾拾拾拾拾
链接:https://www.jianshu.com/p/86be9defb4f5
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- 【云原生】-Docker安装部署分布式数据库 OceanBase
- 这种叫什么手法
- In 2022, the top will be accepted cca shut the list
- Practical Walkthrough | Calculate Daily Average Date or Time Interval in MySQL
- If someone asks you about distributed transactions again, throw this to him
- 易基因:人类tRNA基因位点表现出与衰老相关的DNA高甲基化|研究文章
- Multithreading--the usage of threads and thread pools
- Selected System Design | Design of CAN Bus Controller Based on FPGA (with Code)
- Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解
- 360 released a future-oriented EDR to protect the security of government and enterprise user terminals in an all-round way
猜你喜欢

Re19: Read the paper Paragraph-level Rationale Extraction through Regularization: A case study on European Court

Security思想项目总结
Container Technology - A Simple Understanding of Kubernetes Objects

Matplotlib--plot markers

梅科尔工作室-看鸿蒙设备开发实战笔记四——内核开发

神经网络学习笔记4——自动编码器(含稀疏,堆叠)(更新中)

Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解

jmeter接口压力测试-(二)

async.js入门

MFCC to audio, the effect should not be too funny >V
随机推荐
Quick Start Tutorial for flyway
【HMS core】【FAQ】HMS Toolkit Typical Questions Collection 1
Soft test system architects introductory tutorial | system operation and software maintenance
2022年顶会accepted papers list
JCL 学习
The thread pool method opens the thread -- the difference between submit() and execute()
Re15: Read the paper LEVEN: A Large-Scale Chinese Legal Event Detection Dataset
自适应控制——仿真实验一 用李雅普诺夫稳定性理论设计自适应规律
Adaptive Control - Simulation Experiment 1 Designing Adaptive Laws Using Lyapunov's Stability Theory
idea2021+Activiti【最完整笔记一(基础使用)】
mysql与redis 区别
在机器人行业的专业人士眼里,机器人行业目前的情况如何?
Flink_CDC搭建及简单使用
神经网络学习笔记3——LSTM长短期记忆网络
易基因:人类tRNA基因位点表现出与衰老相关的DNA高甲基化|研究文章
线程池方式开启线程--submit()和execute()的区别
GNOME 新功能:安全启动被禁用时警告用户
Day113. Shangyitong: WeChat login QR code, login callback interface
Neural Network Study Notes 3 - LSTM Long Short-Term Memory Network
(BUG record) No module named PIL