String UIImage实用 extension

2020-10-28  本文已影响0人  _浅墨_
一、String extension,计算字符串长度

String.swift:

import UIKit

extension String {

    func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)

        return ceil(boundingBox.width)
    }
    
}

使用方法:

 let font = UIFont(name: "Times-Bold", size: 23)
 let width = testStr.width(withConstrainedHeight: 60, font: font!)

其中 testStr 为需要计算长度的字符串。

二、UIImage extension,计算长宽比

UIImage.swift:

import UIKit

extension UIImage {
    
    func getImageRatio() -> CGFloat {
        let widthRatio = CGFloat(self.size.width / self.size.height)
        return widthRatio
    }
    
}
三、UIViewController extension:隐藏软键盘

UIViewController.swift:

import UIKit

extension UIViewController {
    
    func hideKeyboardWhenTappedAround() {
        let tapGesture = UITapGestureRecognizer(target: self,
                                                action: #selector(hideKeyboard))
        view.addGestureRecognizer(tapGesture)
    }
    
    @objc func hideKeyboard() {
        view.endEditing(true)
    }
    
}
四、UIImageView extension:缓存图片
import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView:UIImageView{
    
    var imageUrlString:String?
    
    func cacheImageWithLoader(withURL imageURL: String, view:UIView){
        imageUrlString = imageURL
        image = nil
        if imageURL == ""{
            self.image = UIImage(named: "defaultUser")
        } else {
            let url = URL(string: imageURL)
            let request = URLRequest(url: url!)
            
            if let cachedImage = imageCache.object(forKey: imageURL as AnyObject){
                image = (cachedImage as! UIImage)
                view.isHidden = true
            } else {
                URLSession.shared.dataTask(with: request) { (data, response, error) in
                    if error != nil {
                        print(error as Any)
                        return
                    }
                    
                    DispatchQueue.main.async {
                        guard let imageData = UIImage(data: data!) else {return}
                        imageCache.setObject(imageData, forKey: imageURL as AnyObject)
                        if self.imageUrlString == imageURL {
                            self.image = imageData
                        }
                        view.isHidden = true
                    }
                    
                    }.resume()
            }
        }
    }
}

使用方法:

 FetchImageDetailModel.fetchImages(url: "\(Constants.BASE_URL)/photos", id: "\(imageId)") { (imageForPreview) in
    self.imageView.cacheImageWithLoader(withURL: imageForPreview.imageUrl, view: self.backView)
    self.view.reloadInputViews()
 }

其中 imageForPreview 为定义的类全局变量:

 var imageForPreview:FetchImageDetailModel?

另外,FetchImageDetailModel 工具类:

import UIKit
import Alamofire
import SwiftyJSON

class FetchImageDetailModel:NSObject {
    
    var imageUrl:String!
    
    static func fetchImages(url:String, id:String, completionHandler: @escaping (FetchImageDetailModel) -> ()){
        
        let url = "\(url)/\(id)"
        
        let headers:HTTPHeaders = [
            "Authorization": "\(Constants.API_KEY)"
        ]
        
        AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
            
            switch(response.result){
            case .success(_):
                
                let data = JSON(response.value!)
                let modelData = FetchImageDetailModel()
                modelData.imageUrl = data["src"]["large"].string
                
                DispatchQueue.main.async {
                    completionHandler(modelData)
                }
                
                break
                
            case .failure(_):
                print(response.error!)
                break
            }
            
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读