当前位置:网站首页>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
来源:简书
著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.
边栏推荐
- 第1章 Kali与靶机系统
- 还在用Swagger?我推荐这款零代码侵入的接口管理神器
- 【AGC】增长服务2-应用内消息示例
- Neural Network Study Notes 4 - Autoencoder (including sparse, stacked) (updated)
- Multithreading--the usage of threads and thread pools
- 【HarmonyOS】【ARK UI】HarmonyOS ets语言怎么实现双击返回键退出
- Selected System Design | Design of CAN Bus Controller Based on FPGA (with Code)
- async.js入门
- XYplorer 23多语言,最好的管理软件之一
- 【Flume】batchSize和transactionCapacity区别
猜你喜欢

Selected System Design | Design of CAN Bus Controller Based on FPGA (with Code)

【AGC】增长服务2-应用内消息示例

MFCC转音频,效果不要太逗>V<!

【HMS core】【FAQ】HMS Toolkit典型问题合集1

TestNg整合Retry代码

4. yolov5-6.0 ERROR: AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' solution

梅科尔工作室-看鸿蒙设备开发实战笔记七——网络应用开发

ospf2 two-point two-way republish (question 2)

Classes and Objects - 6 Default Member Functions

360发布面向未来的EDR,全方位守护政企用户终端安全
随机推荐
hcip06 ospf special area comprehensive experiment
【Flume】batchSize和transactionCapacity区别
2022全球数字经济大会人工智能专场:AI安全受高度关注
类和对象—6个默认成员函数
MySQL | Subqueries
系统设计精选 | 基于FPGA的CAN总线控制器的设计(附代码)
Redis Desktop Manager 2022.4.2 released
Re16: Read the paper ILDC for CJPE: Indian Legal Documents Corpus for Court Judgment Prediction and Explanation
@RequestBody 和 @ResponseBody 详解
自适应控制——仿真实验一 用李雅普诺夫稳定性理论设计自适应规律
kubernetes的一些命令
Meikle Studio - see the actual combat notes of Hongmeng equipment development five - drive subsystem development
nacos实战项目中的配置
Matplotlib--plot markers
360发布面向未来的EDR,全方位守护政企用户终端安全
Detailed explanation of JVM memory layout, class loading mechanism and garbage collection mechanism
Array of Shell System Learning
Understanding of deadlock
数据库事务,JDBC操作和数据类型
神经网络学习笔记4——自动编码器(含稀疏,堆叠)(更新中)