SnapKit框架解析(二) —— SnapKit应用的一个简单示例(二)

版本记录

版本号 时间
V1.0 2019.07.02 星期二

前言

OC中自动布局可以使用三方比如说Masonry,那么Swift呢?Swift也有很优秀的第三方框架,其中SnapKit就很优秀,接下来几篇我们就一起来看下这个框架。感兴趣的可以看下面几篇文章。
1. SnapKit框架解析(一) —— SnapKit应用的一个简单示例(一)

源码

首先,看下项目工程结构

接着,看下sb中的内容

最后,就是代码了

1. QuizViewController.swift
import UIKit

class QuizViewController: UIViewController {
  /// Curent game state
  var state = State(questions: questions)
  
  /// Current question countdown timer
  var timer: Timer?

  // MARK: - Views
  lazy var viewProgress: UIView = {
    let v = UIView(frame: .zero)
    v.backgroundColor = .green
    
    view.addSubview(v)
    
    return v
  }()
  
  lazy var lblTimer: UILabel = {
    let lbl = UILabel(frame: .zero)
    lbl.layer.cornerRadius = 8
    lbl.layer.borderColor = UIColor.black.cgColor
    lbl.layer.borderWidth = 2
    lbl.textAlignment = .center
    lbl.font = UIFont.systemFont(ofSize: 20, weight: .light)
    lbl.text = "00:10"
    
    view.addSubview(lbl)
    
    return lbl
  }()
  
  lazy var lblQuestion: UILabel = {
    let lbl = UILabel(frame: .zero)
    lbl.textAlignment = .center
    lbl.font = UIFont.systemFont(ofSize: 24, weight: .semibold)
    lbl.text = "Question placeholder"
    lbl.numberOfLines = 0
    
    view.addSubview(lbl)
    
    return lbl
  }()
  
  lazy var btnTrue: UIButton = {
    let btn = UIButton(type: .custom)
    btn.layer.cornerRadius = 12
    btn.backgroundColor = .green
    btn.setTitle("👍True", for: .normal)
    btn.setTitleColor(.black, for: .normal)
    btn.titleLabel?.font = .systemFont(ofSize: 22, weight: .semibold)
    btn.showsTouchWhenHighlighted = true
    btn.addTarget(self, action: #selector(handleAnswer(_:)), for: .touchUpInside)
    
    return btn
  }()
  
  lazy var btnFalse: UIButton = {
    let btn = UIButton(type: .custom)
    btn.layer.cornerRadius = 12
    btn.backgroundColor = .red
    btn.setTitle("👎False", for: .normal)
    btn.setTitleColor(.black, for: .normal)
    btn.titleLabel?.font = .systemFont(ofSize: 22, weight: .semibold)
    btn.showsTouchWhenHighlighted = true
    btn.addTarget(self, action: #selector(handleAnswer(_:)), for: .touchUpInside)
    
    return btn
  }()
  
  lazy var svButtons: UIStackView = {
    let stackView = UIStackView(arrangedSubviews: [btnFalse, btnTrue])
    stackView.alignment = .center
    stackView.spacing = 16
    stackView.axis = .horizontal
    stackView.distribution = .fillEqually
    
    view.addSubview(stackView)
    
    return stackView
  }()
  
  lazy var lblMessage: UILabel = {
    let lbl = UILabel(frame: .zero)
    lbl.numberOfLines = 0
    lbl.backgroundColor = UIColor.black.withAlphaComponent(0.8)
    lbl.textAlignment = .center
    lbl.font = UIFont.systemFont(ofSize: 48, weight: .semibold)
    lbl.alpha = 0
    
    self.navigationController?.view.addSubview(lbl)
    
    return lbl
  }()
  
  // - MARK: Setup
  override func viewDidLoad() {
    super.viewDidLoad()
    
    navigationItem.largeTitleDisplayMode = .always
    navigationController?.navigationBar.prefersLargeTitles = true
    navigationController?.navigationBar.barTintColor = UIColor(red: 1, green: 108.0/255, blue: 0, alpha: 1.0)
    navigationController?.navigationBar.isTranslucent = false
    
    setupConstraints()
    startGame()
  }
}
2. QuizViewController+Constraints.swift
import UIKit
import SnapKit

extension QuizViewController {
  func setupConstraints() {
    updateProgress(to: 0)
    
    lblTimer.snp.makeConstraints { make in
      make.width.equalToSuperview().multipliedBy(0.45).labeled("timerWidth")
      make.height.equalTo(45).labeled("timerHeight")
      make.top.equalTo(viewProgress.snp.bottom).offset(32).labeled("timerTop")
      make.centerX.equalToSuperview().labeled("timerCenterX")
    }
    
    lblQuestion.snp.makeConstraints { make in
      make.top.equalTo(lblTimer.snp.bottom).offset(24)
      make.leading.trailing.equalTo(view.safeAreaLayoutGuide).inset(16)
    }
    
    lblMessage.snp.makeConstraints { make in
      make.edges.equalToSuperview()
    }
    
    svButtons.snp.makeConstraints { make in
      make.leading.trailing.equalTo(lblQuestion)
      make.top.equalTo(lblQuestion.snp.bottom).offset(16)
      make.height.equalTo(80)
    }
  }
  
  func updateProgress(to progress: Double) {
    viewProgress.snp.remakeConstraints { make in
      make.top.equalTo(view.safeAreaLayoutGuide)
      make.width.equalToSuperview().multipliedBy(progress)
      make.height.equalTo(32)
      make.leading.equalToSuperview()
    }
  }
}

// MARK: - Orientation Transition Handling
extension QuizViewController {
  override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    super.willTransition(to: newCollection, with: coordinator)
    // 1
    let isPortrait = UIDevice.current.orientation.isPortrait
    
    // 2
    lblTimer.snp.updateConstraints { make in
      make.height.equalTo(isPortrait ? 45 : 65)
    }
    
    // 3
    lblTimer.font = UIFont.systemFont(ofSize: isPortrait ? 20 : 32, weight: .light)
  }
}
3. QuizViewController+Logic.swift
import UIKit

// MARK: - Game Logic
extension QuizViewController {
  @objc func handleAnswer(_ sender: UIButton) {
    let userSelection = sender == btnTrue
    let isCorrect = state.question.isTrue == userSelection
    
    if isCorrect {
      state.correctAnswers += 1
    }
    
    showMessage(isCorrect: isCorrect)
  }
  
  func showMessage(isCorrect: Bool) {
    lblMessage.text = isCorrect ? "That's correct!\n👍🎉😄" : "Sorry, that's wrong!\n\n👎☠️😢"
    lblMessage.textColor = isCorrect ? .green : .red
    lblMessage.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
    lblMessage.alpha = 0
    timer?.invalidate()
    
    UIView.animate(withDuration: 0.7,
                   delay: 0.0,
                   usingSpringWithDamping: 0.4,
                   initialSpringVelocity: 0.8,
                   options: .curveEaseIn,
                   animations: {
                    self.lblMessage.alpha = 1
                    self.lblMessage.transform = .identity
                   },
                   completion: { _ in
                    UIView.animate(withDuration: 0.15,
                                   delay: 0.35,
                                   animations: {
                                    self.lblMessage.alpha = 0
                                   },
                                   completion: { _ in
                                    self.goToNextQuestion()
                                   })
                   })
  }
  
  func goToNextQuestion() {
    guard !state.isLastQuestion else {
      // This is the last question
      let alert = UIAlertController(title: "Good job!",
                                    message: "You got \(state.correctAnswers) out of \(state.numberOfQuestions) right.",
        preferredStyle: .alert)
      
      alert.addAction(UIAlertAction(title: "Start Over",
                                    style: .default,
                                    handler: { [weak self] _ in self?.startGame() }))
      
      present(alert, animated: true, completion: nil)
      return
    }
    
    goToQuestion(at: state.currentQuestion + 1)
  }
  
  func goToQuestion(at position: Int) {
    state.currentQuestion = position
    
    lblQuestion.text = state.question.title
    navigationItem.title = "SnappyQuiz \(position)/\(state.numberOfQuestions)"
    
    let progress = Double(position) / Double(state.numberOfQuestions)
    updateProgress(to: progress)
    startCountdown()
  }
  
  func startGame() {
    state = State(questions: questions)
    goToQuestion(at: 1)
  }
  
  func startCountdown() {
    lblTimer.text = "00:10"
    
    timer?.invalidate()
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
      guard let self = self else { return }
      
      let currentSeconds = Int((self.lblTimer.text ?? "0").replacingOccurrences(of: ":", with: "")) ?? 1
      
      guard currentSeconds > 1 else {
        timer.invalidate()
        self.goToNextQuestion()
        return
      }
      
      self.lblTimer.text = "00:0\(currentSeconds - 1)"
    }
  }
}
4. Questions.swift
import Foundation

struct Question {
  let title: String
  let isTrue: Bool
}

let questions = [
  ("As far as has ever been reported, no-one has ever seen an ostrich bury its head in the sand.", true),
  ("Approximately one quarter of human bones are in the feet.", true),
  ("Popeye’s nephews were called Peepeye, Poopeye, Pipeye and Pupeye.", true),
  ("In ancient Rome, a special room called a vomitorium was available for diners to purge food in during meals.", false),
  ("The average person will shed 10 pounds of skin during their lifetime.", false),
  ("The Great Wall Of China is visible from the moon.", false),
  ("Virtually all Las Vegas gambling casinos ensure that they have no clocks.", true),
  ("Risotto is a common Italian rice dish.", true),
  ("The prefix \"mega-\" represents one million.", true),
  ("The \"Forbidden City\" is in Beijing.", true),
  ("Hurricanes and typhoons are the same thing.", true),
  ("In Shakespeare's play, Hamlet commits suicide.", false),
  ("An American was the first man in space.", false),
  ("The \"China Syndrome\" is what hostages experience when they begin to feel empathy for their captors.", false),
  ("Other than water, coffee is the world's most popular drink.", true)
].map(Question.init)
5. State.swift
import Foundation

// MARK: - Game State
extension QuizViewController {
  struct State {
    let questions: [Question]
    let numberOfQuestions: Int
    var currentQuestion: Int
    var correctAnswers: Int
    
    init(questions: [Question]) {
      self.questions = questions
      numberOfQuestions = questions.count
      currentQuestion = 1
      correctAnswers = 0
    }
    
    var isLastQuestion: Bool {
      return currentQuestion == numberOfQuestions
    }
    
    var question: Question {
      return questions[currentQuestion - 1]
    }
  }
}

后记

本篇主要讲述了SnapKit自动布局的框架,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容