当前位置:网站首页>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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- 【C和指针第七章】可变参数列表
- [Deep Learning] (Problem Record)
- Linear Regression - Small Batch Stochastic Gradient Descent - Detailed explanation of JVM memory layout, class loading mechanism and garbage collection mechanism
- STM32CubeMX configuration to generate FreeRTOS project
- [HarmonyOS] [ARK UI] How to double-click the return key to exit in HarmonyOS ets language
- JCL learning
- 梅科尔工作室-看鸿蒙设备开发实战笔记四——内核开发
- New in GNOME: Warn users when Secure Boot is disabled
- Quick Start Tutorial for flyway
- OC-手动引用计数内存管理
猜你喜欢

GNOME 新功能:安全启动被禁用时警告用户

第1章 Kali与靶机系统
![【 HMS core 】 【 Analytics Kit] [FAQ] how to solve the payment amount in huawei pay analysis shows zero problem?](/img/f3/b9256fc04d1c9e15c74d2fc14db0fb.png)
【 HMS core 】 【 Analytics Kit] [FAQ] how to solve the payment amount in huawei pay analysis shows zero problem?

Flask's routing (app.route) detailed

加密和安全

MFCC to audio, the effect should not be too funny >V

SST-Calib:结合语义和VO进行时空同步校准的lidar-visual外参标定方法(ITSC 2022)

自适应控制——仿真实验一 用李雅普诺夫稳定性理论设计自适应规律

Quick Start Tutorial for flyway
![[AGC] Growth Service 2 - In-App Message Example](/img/fa/9190e45c1532aec908a6c68706629a.png)
[AGC] Growth Service 2 - In-App Message Example
随机推荐
Neural Network Study Notes 3 - LSTM Long Short-Term Memory Network
mysql安装教程【安装版】
paging
Always remember: one day you will emerge from the chrysalis
Day113. Shangyitong: WeChat login QR code, login callback interface
Database dirty reads, non-repeatable reads, phantom reads and corresponding isolation levels
By building a sequence table - teach you to calculate time complexity and space complexity (including recursion)
wsl操作
【C和指针第七章】可变参数列表
BERT预训练模型系列总结
PyQt5 - Drawing different types of straight lines
死锁的理解
Practical Walkthrough | Calculate Daily Average Date or Time Interval in MySQL
Re19: Read the paper Paragraph-level Rationale Extraction through Regularization: A case study on European Court
Re17: Read the paper Challenges for Information Extraction from Dialogue in Criminal Law
In the robot industry professionals, Mr Robot industry current situation?
(BUG record) No module named PIL
安全提示:Qt中的FreeType
log4js入门
MySQL | Subqueries