美文网首页花落√莫相思swift
54 - Swift 之登录模块

54 - Swift 之登录模块

作者: NetWork小贱 | 来源:发表于2017-07-31 16:16 被阅读28次

    声明:本次更新是对以往学习的知识进行复习。

    一、 登录模块

                    登录模块是每一个App的开发部分,在App中有着很重要的地位,同过登录,我们能获取用户的信息或者一些App使用特权等。

    二 、本Demo 的展示

    Simulator Screen Shot 2017年7月31日 下午3.57.36.png

    三 、 本Demo 使用到的知识点总结

    • 图像的只适应存储它的容器

    • 图像多余,如何裁剪多余的区域

    • 定时器的使用

    • 旋转活动指示器的使用

    • 在异步线程中怎么回到主线程

    • 请求获取数据的解析

    四、相关代码

    1> 登录页面的布局

    // TODO : 登录页面的布局
    func makeLoginUI() -> Void {
        /**
         设置背景
         */
        let bGImageView = UIImageView.init(frame: self.view.frame)
        bGImageView.contentMode = UIViewContentMode.scaleAspectFill
        bGImageView.image = UIImage.init(named: "BgImageView")
        bGImageView.isUserInteractionEnabled = true
        self.view.addSubview(bGImageView)
        
        /**
         Heard ImageView
         */
        let heardImageV = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80))
        heardImageV.center = CGPoint.init(x: self.view.center.x, y: 160)
        heardImageV.layer.masksToBounds = true
        heardImageV.image = UIImage.init(named: "HeaderImageV")
        heardImageV.layer.borderWidth = 6
        heardImageV.layer.backgroundColor = UIColor.cyan.cgColor
        heardImageV.layer.cornerRadius = heardImageV.bounds.width * 0.5
        heardImageV.contentMode = .scaleAspectFill
        bGImageView.addSubview(heardImageV)
        
        /**
         账号
         */
        let AccountLable = UILabel.init(frame: CGRect.init(x: 40, y:heardImageV.frame.maxY+30
    , width: 40, height: 30))
        AccountLable.text = "账户:"
        bGImageView.addSubview(AccountLable)
        
        AccountTextField = UITextField.init(frame: CGRect.init(x: AccountLable.frame.maxX+10, y: heardImageV.frame.maxY + 32, width: bGImageView.frame.width - 90 - AccountLable.frame.width, height: 30))
        AccountTextField?.placeholder = "请输入您的账户"
        bGImageView.addSubview(AccountTextField!)
        
        let line = UIView.init(frame: CGRect.init(x: 40, y: AccountLable.frame.maxY, width: bGImageView.frame.width - 80, height: 1))
        line.backgroundColor = UIColor.gray
        bGImageView.addSubview(line)
        
        /**
         密码
         */
        let passWLable = UILabel.init(frame: CGRect.init(x: 40, y: line.frame.maxY+40, width: 40, height: 30))
        passWLable.text = "密码:"
        bGImageView.addSubview(passWLable)
        
        passWTextField = UITextField.init(frame: CGRect.init(x: passWLable.frame.maxX+10, y: line.frame.maxY + 42, width: bGImageView.frame.width - passWLable.frame.width - 90, height: 30))
        passWTextField?.placeholder = "请输入密码"
        bGImageView.addSubview(passWTextField!)
        
        let lineV = UIView .init(frame: CGRect.init(x: 40, y: passWLable.frame.maxY, width: bGImageView.frame.width - 80, height: 1))
        lineV.backgroundColor = UIColor.gray
        bGImageView.addSubview(lineV)
    
        /**
         点击按钮
         */
        let loginBtn = UIButton.init(frame: CGRect.init(x: 40, y: lineV.frame.maxY + 50, width: bGImageView.frame.width - 80, height: 40))
        loginBtn.setTitle("登录", for: .normal)
        loginBtn.setTitleColor(UIColor.black, for: .normal)
        loginBtn.layer.cornerRadius = 6
        loginBtn.addTarget(self, action:#selector(click(_:)), for:.touchUpInside)
        loginBtn.layer.borderColor = UIColor.gray.cgColor
        loginBtn.layer.borderWidth = 1
        bGImageView.addSubview(loginBtn)
    }
    

    2> 自动消失的提示

    // TODO : 简短提示
    func autoAlertView(message:String) -> Void {
        let autoAlert = UIAlertController.init(title: "", message: message, preferredStyle: .alert)
        self.present(autoAlert, animated: true) { 
            self.timer = Timer.init(timeInterval: 10, repeats: false, block: { (time) in
                autoAlert.dismiss(animated: true, completion:{
                   self.timer?.invalidate()
                })
            })
            self.timer?.fire()
        }
    }
    

    3> 活动指示器的提示

    // TODO : 活动指示器的提示
    func activityIndicator(isFinsh:Bool) -> Void {
        if isFinsh {
            underView?.removeFromSuperview()
            return;
        }
        underView = UIView.init(frame: self.view.frame)
        underView?.backgroundColor = UIColor.clear
        self.view.addSubview(underView!)
        
        let activitV = UIActivityIndicatorView.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80))
        activitV.center = CGPoint.init(x: underView!.center.x, y: underView!.center.y)
        activitV.backgroundColor = UIColor.gray
        activitV.activityIndicatorViewStyle = .whiteLarge
        activitV.layer.cornerRadius = 6
        underView?.addSubview(activitV)
        activitV.startAnimating()
    }
    
    

    4> 数据的下载

    func loadData() -> Void {
        self.activityIndicator(isFinsh: false)
        let url = URL.init(string: "http://api.3g.ifeng.com/clientShortNews?type=beauty")
        let request = URLRequest.init(url: url!)
        let DataTask = URLSession.shared.dataTask(with: request) { (data, resp, error) in
            self.activityIndicator(isFinsh: true)
            if data != nil && error == nil {
                let dict = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                DispatchQueue.main.async(execute: {
                     let  Vc = HomeViewController.init()
                     Vc.dataDictionary = (dict as! NSDictionary)
                     let NavVc = UINavigationController.init(rootViewController: Vc)
                     self.present(NavVc, animated: true, completion: nil)
                })
            }
        }
        DataTask.resume()
    }
    

    5> 本Demo的效果展示

    Untitled.gif

    6> 完整代码

    
    import UIKit
    
    class LoginViewController: UIViewController {
    
    var AccountTextField:UITextField?
    var passWTextField:UITextField?
    var timer:Timer?
    var underView:UIView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNavition()
        self.makeLoginUI()
        // Do any additional setup after loading the view.
    }
    
    // TODO : 设置导航
    func setNavition() -> Void {
        self.navigationItem.title = "登录"
    }
    
    // TODO : 登录页面的布局
    func makeLoginUI() -> Void {
        /**
         设置背景
         */
        let bGImageView = UIImageView.init(frame: self.view.frame)
        bGImageView.contentMode = UIViewContentMode.scaleAspectFill
        bGImageView.image = UIImage.init(named: "BgImageView")
        bGImageView.isUserInteractionEnabled = true
        self.view.addSubview(bGImageView)
        
        /**
         Heard ImageView
         */
        let heardImageV = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80))
        heardImageV.center = CGPoint.init(x: self.view.center.x, y: 160)
        heardImageV.layer.masksToBounds = true
        heardImageV.image = UIImage.init(named: "HeaderImageV")
        heardImageV.layer.borderWidth = 6
        heardImageV.layer.backgroundColor = UIColor.cyan.cgColor
        heardImageV.layer.cornerRadius = heardImageV.bounds.width * 0.5
        heardImageV.contentMode = .scaleAspectFill
        bGImageView.addSubview(heardImageV)
        
        /**
         账号
         */
        let AccountLable = UILabel.init(frame: CGRect.init(x: 40, y:heardImageV.frame.maxY+30
    , width: 40, height: 30))
        AccountLable.text = "账户:"
        bGImageView.addSubview(AccountLable)
        
        AccountTextField = UITextField.init(frame: CGRect.init(x: AccountLable.frame.maxX+10, y: heardImageV.frame.maxY + 32, width: bGImageView.frame.width - 90 - AccountLable.frame.width, height: 30))
        AccountTextField?.placeholder = "请输入您的账户"
        bGImageView.addSubview(AccountTextField!)
        
        let line = UIView.init(frame: CGRect.init(x: 40, y: AccountLable.frame.maxY, width: bGImageView.frame.width - 80, height: 1))
        line.backgroundColor = UIColor.gray
        bGImageView.addSubview(line)
        
        /**
         密码
         */
        let passWLable = UILabel.init(frame: CGRect.init(x: 40, y: line.frame.maxY+40, width: 40, height: 30))
        passWLable.text = "密码:"
        bGImageView.addSubview(passWLable)
        
        passWTextField = UITextField.init(frame: CGRect.init(x: passWLable.frame.maxX+10, y: line.frame.maxY + 42, width: bGImageView.frame.width - passWLable.frame.width - 90, height: 30))
        passWTextField?.placeholder = "请输入密码"
        bGImageView.addSubview(passWTextField!)
        
        let lineV = UIView .init(frame: CGRect.init(x: 40, y: passWLable.frame.maxY, width: bGImageView.frame.width - 80, height: 1))
        lineV.backgroundColor = UIColor.gray
        bGImageView.addSubview(lineV)
    
        /**
         点击按钮
         */
        let loginBtn = UIButton.init(frame: CGRect.init(x: 40, y: lineV.frame.maxY + 50, width: bGImageView.frame.width - 80, height: 40))
        loginBtn.setTitle("登录", for: .normal)
        loginBtn.setTitleColor(UIColor.black, for: .normal)
        loginBtn.layer.cornerRadius = 6
        loginBtn.addTarget(self, action:#selector(click(_:)), for:.touchUpInside)
        loginBtn.layer.borderColor = UIColor.gray.cgColor
        loginBtn.layer.borderWidth = 1
        bGImageView.addSubview(loginBtn)
    }
    
    
    // TODO : 登录事件的触发
    func click(_ btn:UIButton) -> Void {
        if (AccountTextField != nil) && (AccountTextField?.text?.characters.count != 0) {
            if self.passWTextField != nil && passWTextField?.text?.characters.count != 0 {
                self.loadData()
            }else{
                self.autoAlertView(message: "请填写密码")
            }
        }else{
            self.autoAlertView(message: "请填写账户")
        }
    }
    
    // TODO : 简短提示
    func autoAlertView(message:String) -> Void {
        let autoAlert = UIAlertController.init(title: "", message: message, preferredStyle: .alert)
        self.present(autoAlert, animated: true) { 
            self.timer = Timer.init(timeInterval: 10, repeats: false, block: { (time) in
                autoAlert.dismiss(animated: true, completion:{
                   self.timer?.invalidate()
                })
            })
            self.timer?.fire()
        }
    }
    
    // TODO : 活动指示器的提示
    func activityIndicator(isFinsh:Bool) -> Void {
        if isFinsh {
            underView?.removeFromSuperview()
            return;
        }
        underView = UIView.init(frame: self.view.frame)
        underView?.backgroundColor = UIColor.clear
        self.view.addSubview(underView!)
        
        let activitV = UIActivityIndicatorView.init(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80))
        activitV.center = CGPoint.init(x: underView!.center.x, y: underView!.center.y)
        activitV.backgroundColor = UIColor.gray
        activitV.activityIndicatorViewStyle = .whiteLarge
        activitV.layer.cornerRadius = 6
        underView?.addSubview(activitV)
        activitV.startAnimating()
    }
    
    
    func loadData() -> Void {
        self.activityIndicator(isFinsh: false)
        let url = URL.init(string: "http://api.3g.ifeng.com/clientShortNews?type=beauty")
        let request = URLRequest.init(url: url!)
        let DataTask = URLSession.shared.dataTask(with: request) { (data, resp, error) in
            self.activityIndicator(isFinsh: true)
            if data != nil && error == nil {
                let dict = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                DispatchQueue.main.async(execute: {
                     let  Vc = HomeViewController.init()
                     Vc.dataDictionary = (dict as! NSDictionary)
                     let NavVc = UINavigationController.init(rootViewController: Vc)
                     self.present(NavVc, animated: true, completion: nil)
                })
            }
        }
        DataTask.resume()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    7> 登录成功后的页面

    
    import UIKit
    
    
    
    class HomeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var dataDictionary:NSDictionary?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "首页"
        let RootTableView = UITableView.init(frame: self.view.frame, style: .plain)
        RootTableView.delegate = self
        RootTableView.dataSource = self
        self.view.addSubview(RootTableView)
        // Do any additional setup after loading the view.
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         return 60
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return (self.dataDictionary?["list"] as! NSArray).count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell_login")
        if cell == nil {
             cell = UITableViewCell.init(style: .value1, reuseIdentifier: "cell_login")
        }
        let  arrayList = self.dataDictionary?["list"] as! NSArray
        let dict = arrayList[indexPath.row] as! NSDictionary
        cell?.textLabel?.text = (dict["name"] as! String)
        cell?.detailTextLabel?.text = (dict["type"] as! String)
        return cell!
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    

    相关文章

      网友评论

        本文标题:54 - Swift 之登录模块

        本文链接:https://www.haomeiwen.com/subject/ludrlxtx.html