Swift5+MVC+WanAndroid Project (pure code)

Github source address

preface

I have learned Swift5 recently, and made a simple APP for practice using WanAndroid open API, realizing some common functions (it is good for beginners to practice), but the UI page is not very beautiful, please forgive me!

Project screenshots







The main function

  • Home page, project, hot, my four modules;
  • Login registration function;
  • Search function: popular search, search history;
  • Article list, grid layout;
  • Tab switching function
  • Automatic rotation chart
  • Custom up/down refresh
  • Toast to remind
  • Network request encapsulation
  • Common View extension

Major Open Source frameworks

  • Pod ‘Moya’// Network secondary encapsulation
  • pod ‘PrintBeautifulLog’
  • Pod ‘Alamofire’ # network, ‘~> 4.7’
  • Pod ‘MJRefresh’ # refresh
  • Pod ‘LLCycleScrollView’ #
  • pod ‘EmptyDataSet-Swift’
  • pod ‘MBProgressHUD’
  • pod ‘HandyJSON’
  • Pod ‘Kingfisher’ # picture
  • Pod ‘Then’ # syntax sugar
  • Pod ‘SnapKit’, ‘~ > 4.2.0’
  • Pod ‘SnapKitExtend’ # Automatic layout extension
  • pod ‘SVProgressHUD’
  • pod ‘MBProgressHUD’
  • Pod ‘Reusable’ # Reusable
  • Pod ‘Tabman’ # TAB navigation
  • pod ‘JXSegmentedView’
  • Pod ‘Toast – Swift,’ ‘~ > 5.0.1’

The main code

class MainViewController: UITabBarController ,UINavigationControllerDelegate{
    
    override func viewDidLoad(a) {
        super.viewDidLoad()
        
        createTabs();
        
        // This setting works. But to see the source code comment means that the entire TabBar setup -!
        UITabBar.appearance().tintColor = UIColor.red        
    }

    
    // Go to the search page
    @objc func clickSearch(a){
        //self.navigationController? .pushViewController(SearchArcticleViewController(), animated: true)
    }
    
    / / create tabs
    func createTabs(a){
        // Home Tab VC
        let homeVC = HomeVC(a); homeVC.tabBarItem= UITabBarItem(title: "Home page",  image: UIImage(named: "home_tabbar_night_32x32_"),
                                      selectedImage: UIImage(named: "home_tabbar_press_32x32_"));
        
        let homeNVC = UINavigationController(rootViewController: homeVC);
        / / homeNVC. NavigationItem. Title = "home page";
        
        
        // Knowledge base
        let knowledgeVC = ProjectVC(a); knowledgeVC.tabBarItem= UITabBarItem(title: "Project",  image: UIImage(named: "huoshan_tabbar_night_32x32_"),
                                      selectedImage: UIImage(named: "huoshan_tabbar_press_32x32_"));
        let knowledgeNVC = UINavigationController(rootViewController: knowledgeVC);
                 
        / / hot
        let hotVC = HotTabVC(a); hotVC.tabBarItem= UITabBarItem(title: "Hot", image: UIImage(named: "weitoutiao_tabbar_night_32x32_"),
                                      selectedImage: UIImage(named: "weitoutiao_tabbar_press_32x32_"));
        let hotNVC = UINavigationController(rootViewController: hotVC);
        
    
        / / to me
        let myVC = MyTabViewVC()
        myVC.tabBarItem = UITabBarItem(title: "I",  image: UIImage(named: "mine_tabbar_night_32x32_"),
                                      selectedImage: UIImage(named: "mine_tabbar_press_32x32_"))
        let myNVC = UINavigationController(rootViewController: myVC)
        
                
        self.viewControllers =[homeVC, knowledgeVC, hotVC, myVC]; }}Copy the code

HttpUtils Encapsulates network requests

enum MethodType {
    case get
    case post
}

class HttpUtils {
    class  func requestData<T:HandyJSON> (url : String ,type : MethodType ,params : [String:Any]? = nil.callBack : @escaping (_ result : T?). - > ()){
        let method =  type = = .get ? HTTPMethod.get :HTTPMethod.post
        
        let headers: HTTPHeaders = [
            "Cookie": ""
        ]
        print("The request URL -- -- -- -- --\(baseUrl+url)")
        Alamofire.request(baseUrl+url, method: method, parameters: params, encoding: URLEncoding.default
            , headers: nil).responseJSON {(response) in
                
                / / 1. Check result response. Result. IsSuccess
                guard let result = response.result.value else {
                    callBack(nil)
                    print("Request failed"\(response.result.error)")
                    return
                }
                //2. Result callback
                // callBack(result)
                
                let model  =   JSONDeserializer<BaseResponse<T>>.deserializeFrom(dict: result as? [String : Any] )
                callBack(model?.data)
                
                print("Request successful -----\(response.request?.url)")
                //print(response.result.value)
                MyLog(log: response.result.value)
                
        }
    }
    
    
    class  func requestDataArray<T:HandyJSON> (url : String ,type : MethodType ,params : [String:Any]? = nil.callBack : @escaping (_ result : [T]?) -> ())  {
        let method =  type = = .get ? HTTPMethod.get :HTTPMethod.post
        
        let headers: HTTPHeaders = [
            "Cookie": ""
        ]
        print("The request URL -- -- -- -- --\(baseUrl+url)")
        Alamofire.request(baseUrl+url, method: method, parameters: params, encoding: URLEncoding.default
            , headers: nil).responseJSON {(response) in
                
                / / 1. Check result response. Result. IsSuccess
                guard let result = response.result.value else {
                    callBack(nil)
                    print("Request failed"\(response.result.error)")
                    return
                }
                //2. Result callback
                // callBack(result)
                let model  =   JSONDeserializer<BaseResponseArray<T>>.deserializeFrom(dict: result as? [String : Any] )
                callBack(model?.data)
                
                print("Request successful -----\(response.request?.url)")
                //print(response.result.value)
                MyLog(log: response.result.value)
                
        }
    }
}
Copy the code

UILabel extension

import UIKit

extension UILabel{
    /** UILabel traversal constructor -parameter text: text -parameter textColor: text color -parameter fontSize: Text size -parameter numOfLines: number of text lines -parameter alignment */
    convenience init(text:String? ._ textColor:UIColor = UIColor.darkGray,
                     _ fontSize:CGFloat = 16._ numOfLines:Int = 0._ alignment:NSTextAlignment = .left) {
        self.init(a)self.text = text
        self.textColor = textColor
        self.font = UIFont.systemFont(ofSize: fontSize)
        self.numberOfLines = numOfLines
        self.textAlignment = alignment
        
        self.sizeToFit()
    }
}

/** //UILabel adaptive height -parameter label: UILabel control -parameter width: text display width -parameter style: Text styles (including line height, word spacing, etc.) Don't set the calculation will not be accurate) let style = NSMutableParagraphStyle. The init () / / line spacing style.css. LineSpacing = 10. Label attributedText = NSAttributedString(string: string, attributes: [NSAttributedString.Key.paragraphStyle: // Let boundingRect = autoLabel(label: label,width: screenWidth-40,style: style) label. Frame = CGRect(x: 20, y: navHeight+100, width: boundingRect.width, height: boundingRect.height) */
  func autoLabel(label:UILabel , width:CGFloat.style:NSMutableParagraphStyle)-> CGRect{
      let options: NSStringDrawingOptions = .usesLineFragmentOrigin
      let str: NSString = label.text! as NSString
      let boundingRect = str.boundingRect(with: CGSize(width: width, height: 0), options: options, attributes: [NSAttributedString.Key.font:label.font, NSAttributedString.Key.paragraphStyle:style], context: nil)
      return boundingRect
  }
Copy the code

UIColor extension

import UIKit

extension UIColor {
  convenience init(r:UInt32 ,g:UInt32 , b:UInt32 , a:CGFloat = 1.0) {
      self.init(red: CGFloat(r) / 255.0,
                green: CGFloat(g) / 255.0,
                blue: CGFloat(b) / 255.0,
                alpha: a)
  }
}


//MRAK: apply the default color
extension UIColor {
  class var background: UIColor {
      
      return UIColor(r: 242, g: 242, b: 242)}class var theme: UIColor {
      return UIColor(r: 29, g: 221, b: 43)}/** get the color from the hexadecimal color value string, e.g. #ff0000, ff0000 -parameter alpha: hexadecimal string RGB */
  static func withHex(hexString hex: String.alpha:CGFloat = 1) -> UIColor {
      // remove whitespace, etc
      var cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
      / / remove #
      if (cString.hasPrefix("#")) {
          cString = (cString as NSString).substring(from: 1)}// Must be 6 digits
      if (cString.count ! = 6) {
          return UIColor.gray
      }
      // The color value of red
      let rString = (cString as NSString).substring(to: 2)
      let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
      let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
      // String conversion
      var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0
      Scanner(string: rString).scanHexInt32(&r)
      Scanner(string: gString).scanHexInt32(&g)
      Scanner(string: bString).scanHexInt32(&b)
      
      return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
  }
  
  -parameter hexInt: hexadecimal value -parameter alpha: transparency - returns: color */
  static func withHex(hexInt hex:Int32.alpha:CGFloat = 1) -> UIColor {
      let r = CGFloat((hex & 0xff0000) >> 16) / 255
      let g = CGFloat((hex & 0xff00) >> 8) / 255
      let b = CGFloat(hex & 0xff) / 255
      return UIColor(red: r, green: g, blue: b, alpha: alpha)
  }
  
  /** Get the color through rgb-parameter red: red - parameter green: green - parameter blue: blue - returns: color */
  static func withRGB(_ red:CGFloat._ green:CGFloat._ blue:CGFloat) -> UIColor {
      return UIColor.withRGBA(red, green, blue, 1)}/** Get the color through rgb-parameter red: red -parameter green: green -parameter blue: blue -parameter alpha: transparency - returns: Color * /
  static func withRGBA(_ red:CGFloat._ green:CGFloat._ blue:CGFloat._ alpha:CGFloat) -> UIColor {
      return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: alpha)
  }
}
Copy the code