版本記錄
| 版本號(hào) | 時(shí)間 |
|---|---|
| V1.0 | 2020.02.17 星期一 |
前言
iOS中有關(guān)視圖控件用戶能看到的都在UIKit框架里面,用戶交互也是通過(guò)UIKit進(jìn)行的。感興趣的參考上面幾篇文章。
1. UIKit框架(一) —— UIKit動(dòng)力學(xué)和移動(dòng)效果(一)
2. UIKit框架(二) —— UIKit動(dòng)力學(xué)和移動(dòng)效果(二)
3. UIKit框架(三) —— UICollectionViewCell的擴(kuò)張效果的實(shí)現(xiàn)(一)
4. UIKit框架(四) —— UICollectionViewCell的擴(kuò)張效果的實(shí)現(xiàn)(二)
5. UIKit框架(五) —— 自定義控件:可重復(fù)使用的滑塊(一)
6. UIKit框架(六) —— 自定義控件:可重復(fù)使用的滑塊(二)
7. UIKit框架(七) —— 動(dòng)態(tài)尺寸UITableViewCell的實(shí)現(xiàn)(一)
8. UIKit框架(八) —— 動(dòng)態(tài)尺寸UITableViewCell的實(shí)現(xiàn)(二)
9. UIKit框架(九) —— UICollectionView的數(shù)據(jù)異步預(yù)加載(一)
10. UIKit框架(十) —— UICollectionView的數(shù)據(jù)異步預(yù)加載(二)
11. UIKit框架(十一) —— UICollectionView的重用、選擇和重排序(一)
12. UIKit框架(十二) —— UICollectionView的重用、選擇和重排序(二)
13. UIKit框架(十三) —— 如何創(chuàng)建自己的側(cè)滑式面板導(dǎo)航(一)
14. UIKit框架(十四) —— 如何創(chuàng)建自己的側(cè)滑式面板導(dǎo)航(二)
15. UIKit框架(十五) —— 基于自定義UICollectionViewLayout布局的簡(jiǎn)單示例(一)
16. UIKit框架(十六) —— 基于自定義UICollectionViewLayout布局的簡(jiǎn)單示例(二)
17. UIKit框架(十七) —— 基于自定義UICollectionViewLayout布局的簡(jiǎn)單示例(三)
18. UIKit框架(十八) —— 基于CALayer屬性的一種3D邊欄動(dòng)畫的實(shí)現(xiàn)(一)
19. UIKit框架(十九) —— 基于CALayer屬性的一種3D邊欄動(dòng)畫的實(shí)現(xiàn)(二)
20. UIKit框架(二十) —— 基于UILabel跑馬燈類似效果的實(shí)現(xiàn)(一)
21. UIKit框架(二十一) —— UIStackView的使用(一)
22. UIKit框架(二十二) —— 基于UIPresentationController的自定義viewController的轉(zhuǎn)場(chǎng)和展示(一)
23. UIKit框架(二十三) —— 基于UIPresentationController的自定義viewController的轉(zhuǎn)場(chǎng)和展示(二)
24. UIKit框架(二十四) —— 基于UICollectionViews和Drag-Drop在兩個(gè)APP間的使用示例 (一)
25. UIKit框架(二十五) —— 基于UICollectionViews和Drag-Drop在兩個(gè)APP間的使用示例 (二)
26. UIKit框架(二十六) —— UICollectionView的自定義布局 (一)
27. UIKit框架(二十七) —— UICollectionView的自定義布局 (二)
28. UIKit框架(二十八) —— 一個(gè)UISplitViewController的簡(jiǎn)單實(shí)用示例 (一)
29. UIKit框架(二十九) —— 一個(gè)UISplitViewController的簡(jiǎn)單實(shí)用示例 (二)
30. UIKit框架(三十) —— 基于UICollectionViewCompositionalLayout API的UICollectionViews布局的簡(jiǎn)單示例(一)
31. UIKit框架(三十一) —— 基于UICollectionViewCompositionalLayout API的UICollectionViews布局的簡(jiǎn)單示例(二)
32. UIKit框架(三十二) —— 替換Peek and Pop交互的基于iOS13的Context Menus(一)
33. UIKit框架(三十三) —— 替換Peek and Pop交互的基于iOS13的Context Menus(二)
34. UIKit框架(三十四) —— Accessibility的使用(一)
源碼
1. Swift
首先看下工程組織結(jié)構(gòu)

下面看下sb中的內(nèi)容

接著就是源碼了
1. InstructionViewModel.swift
import Foundation
enum RecipeInstructionType {
case ingredient, cookingInstructions
}
struct InstructionViewModel {
let recipe: Recipe?
var type: RecipeInstructionType
var ingredientsState: [Bool] = []
var directionsState: [Bool] = []
init(recipe: Recipe, type: RecipeInstructionType) {
self.recipe = recipe
self.type = type
if let ingredients = recipe.ingredients {
ingredientsState = [Bool](repeating: false, count:ingredients.count)
}
if let directions = recipe.directions {
directionsState = [Bool](repeating: false, count:directions.count)
}
}
mutating func numberOfItems() -> Int {
switch type {
case .ingredient:
if let ingredients = recipe?.ingredients {
return ingredients.count
}
case .cookingInstructions:
if let directions = recipe?.directions {
return directions.count
}
}
return 0
}
func numberOfSections() -> Int {
return 1
}
func itemFor(_ index: Int) -> String? {
switch type {
case .ingredient:
if let ingredients = recipe?.ingredients {
return ingredients[index]
}
case .cookingInstructions:
if let directions = recipe?.directions {
return directions[index]
}
}
return nil
}
func getStateFor(_ index: Int) -> Bool {
switch type {
case .ingredient:
return ingredientsState[index]
case .cookingInstructions:
return directionsState[index]
}
}
mutating func selectItemFor(_ index: Int) {
switch type {
case .ingredient:
ingredientsState[index].toggle()
case .cookingInstructions:
directionsState[index].toggle()
}
}
}
2. Recipe.swift
import UIKit
// Data from: http://damndelicious.net/recipe-index/
enum RecipeDifficulty {
case unknown
case rating(Int)
}
extension RecipeDifficulty {
init?(value: Int) {
if value > 0 && value <= 5 {
self = .rating(value)
} else {
self = .unknown
}
}
}
struct Recipe {
let name: String
let difficulty: RecipeDifficulty
let photo: UIImage?
let photoDescription: String
let prepTime: Int
let cookTime: Int
let yield: Int
let ingredients: [String]?
let directions: [String]?
}
extension Recipe {
init?(dict: [String: AnyObject]) {
guard
let name = dict["name"] as? String,
let rawDifficulty = dict["difficulty"] as? Int,
let difficulty = RecipeDifficulty(value: rawDifficulty),
let prepTime = dict["prepTime"] as? Int,
let cookTime = dict["cookTime"] as? Int,
let yield = dict["yield"] as? Int,
let ingredients = dict["ingredients"] as? [String],
let directions = dict["directions"] as? [String],
let photoDescription = dict["photoDescription"] as? String
else {
return nil
}
self.name = name
self.difficulty = difficulty
self.prepTime = prepTime
self.cookTime = cookTime
self.yield = yield
self.ingredients = ingredients
self.directions = directions
self.photoDescription = photoDescription
if let imageName = dict["imageName"] as? String, !imageName.isEmpty {
photo = UIImage(named: imageName)
} else {
photo = nil
}
}
}
// MARK: - Load Sample Data
extension Recipe {
static func loadDefaultRecipe() -> [Recipe]? {
return self.loadRecipeFrom("RecipeList")
}
static func loadRecipeFrom(_ plistName: String) -> [Recipe]? {
guard
let path = Bundle.main.path(forResource: plistName, ofType: "plist"),
let array = NSArray(contentsOfFile: path) as? [[String: AnyObject]]
else {
return nil
}
return array.compactMap { Recipe(dict: $0) }
}
}
3. RecipeInstructionsViewController.swift
import UIKit
class RecipeInstructionsViewController: UITableViewController {
private var headerView: UIView!
private var instructionViewModel: InstructionViewModel!
var recipe: Recipe!
var didLikeFood = true
@IBOutlet var likeButton: UIButton!
@IBOutlet var backButton: UIButton!
@IBOutlet var dishImageView: UIImageView!
@IBOutlet var dishLabel: UILabel!
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
assert(recipe != nil)
backButton.accessibilityLabel = "back"
backButton.accessibilityTraits = UIAccessibilityTraits.button
isLikedFood(true)
instructionViewModel = InstructionViewModel(recipe: recipe, type: .ingredient)
setupRecipe()
setupTableView()
}
// MARK: - Action Outlets
@IBAction func likeButtonPressed(_ sender: AnyObject) {
isLikedFood(!didLikeFood)
}
func isLikedFood(_ liked: Bool) {
if liked {
likeButton.setTitle("??", for: .normal)
likeButton.accessibilityLabel = "Like"
likeButton.accessibilityTraits = UIAccessibilityTraits.button
didLikeFood = true
} else {
likeButton.setTitle("??", for: .normal)
likeButton.accessibilityLabel = "Dislike"
likeButton.accessibilityTraits = UIAccessibilityTraits.button
didLikeFood = false
}
}
@IBAction func toggleSegment(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 { // Ingredients
instructionViewModel.type = .ingredient
} else { //Instruction
instructionViewModel.type = .cookingInstructions
}
tableView.reloadData()
}
@IBAction func tapBackButton(_ sender: AnyObject) {
navigationController?.popViewController(animated: true)
}
// MARK: - TableView Data Source
override func numberOfSections(in tableView: UITableView) -> Int {
return instructionViewModel.numberOfSections()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return instructionViewModel.numberOfItems()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: InstructionCell.self), for: indexPath) as! InstructionCell
if let description = instructionViewModel.itemFor(indexPath.item) {
cell.configure(description)
}
let strike = instructionViewModel.getStateFor(indexPath.item)
cell.shouldStrikeThroughText(strike)
return cell
}
// MARK: - TableView Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
instructionViewModel.selectItemFor(indexPath.item)
let cell = tableView.cellForRow(at: indexPath) as! InstructionCell
let strike = instructionViewModel.getStateFor(indexPath.item)
cell.shouldStrikeThroughText(strike)
}
}
// MARK: - Setup
extension RecipeInstructionsViewController {
func setupRecipe() {
dishImageView.image = recipe.photo
dishLabel.text = recipe.name
}
func setupTableView() {
tableView.estimatedRowHeight = 79
tableView.rowHeight = UITableView.automaticDimension
}
}
4. RecipeListViewController.swift
import UIKit
class RecipeListViewController: UITableViewController {
var recipes: [Recipe] = []
var selectedRecipe: Recipe?
override func viewDidLoad() {
super.viewDidLoad()
if let seedRecipe = Recipe.loadDefaultRecipe() {
recipes += seedRecipe
recipes = recipes.sorted(by: { $0.name < $1.name })
}
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableView.automaticDimension
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showRecipe" {
if let vc = segue.destination as? RecipeInstructionsViewController {
vc.recipe = selectedRecipe
}
}
}
// MARK: - TableView Data Source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RecipeCell.self), for: indexPath) as! RecipeCell
let recipe = recipes[indexPath.item]
cell.configureCell(with: recipe)
return cell
}
// MARK: - TableView Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
selectedRecipe = recipes[indexPath.item]
performSegue(withIdentifier: "showRecipe", sender: self)
}
}
5. InstructionCell.swift
import UIKit
class InstructionCell: UITableViewCell {
@IBOutlet var checkmarkButton: UIButton!
@IBOutlet var descriptionLabel: UILabel!
func configure(_ description: String) {
descriptionLabel.attributedText = nil
descriptionLabel.text = description
}
@IBAction func checkmarkTapped(_ sender: AnyObject) {
shouldStrikeThroughText(!checkmarkButton.isSelected)
}
func shouldStrikeThroughText(_ strikeThrough: Bool) {
guard let text = descriptionLabel.text else {
return
}
let attributeString = NSMutableAttributedString(string: text)
// 1
checkmarkButton.isAccessibilityElement = false
if strikeThrough {
// 2
descriptionLabel.accessibilityLabel = "Completed: \(text)"
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(text.startIndex..., in: text))
} else {
// 3
descriptionLabel.accessibilityLabel = "Uncompleted: \(text)"
}
let buttonImage = strikeThrough ? UIImage(named: "icon-check") : UIImage(named: "icon-empty")
checkmarkButton.setImage(buttonImage, for: .normal)
descriptionLabel.attributedText = attributeString
}
}
6. RecipeCell.swift
import UIKit
class RecipeCell: UITableViewCell {
@IBOutlet var roundedBackgroundView: UIView!
@IBOutlet var foodImageView: UIImageView!
@IBOutlet var dishNameLabel: UILabel!
@IBOutlet var difficultyLabel: UILabel!
var difficultyValue: RecipeDifficulty = .unknown
override func awakeFromNib() {
super.awakeFromNib()
styleAppearance()
}
func configureCell(with recipe:Recipe) {
dishNameLabel.text = recipe.name
foodImageView.image = recipe.photo
difficultyValue = recipe.difficulty
difficultyLabel.text = difficultyString
applyAccessibility(recipe)
}
var difficultyString: String {
switch difficultyValue {
case .unknown:
return ""
case .rating(let value):
var string = ""
for _ in 0..<value {
string.append("??")
}
return string
}
}
func styleAppearance() {
roundedBackgroundView.layer.cornerRadius = 3.0
roundedBackgroundView.layer.masksToBounds = false
roundedBackgroundView.layer.shadowOffset = CGSize(width: 0, height: 0)
roundedBackgroundView.layer.shadowColor = #colorLiteral(red: 0.05439098924, green: 0.1344551742, blue: 0.1884709597, alpha: 1).cgColor
roundedBackgroundView.layer.shadowRadius = 1.0
roundedBackgroundView.layer.shadowOpacity = 0.3
foodImageView.layer.cornerRadius = 3.0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
// MARK: Accessibility
extension RecipeCell {
func applyAccessibility(_ recipe: Recipe) {
// 1
foodImageView.accessibilityTraits = UIAccessibilityTraits.image
// 2
foodImageView.accessibilityLabel = recipe.photoDescription
// 1
difficultyLabel.isAccessibilityElement = true
// 2
difficultyLabel.accessibilityTraits = UIAccessibilityTraits.none
// 3
difficultyLabel.accessibilityLabel = "Difficulty Level"
// 4
switch recipe.difficulty {
case .unknown:
difficultyLabel.accessibilityValue = "Unknown"
case .rating(let value):
difficultyLabel.accessibilityValue = "\(value)"
}
difficultyLabel.font = UIFont.preferredFont(forTextStyle: .body)
difficultyLabel.adjustsFontForContentSizeCategory = true
}
}
后記
本篇主要講述了Accessibility的使用,感興趣的給個(gè)贊或者關(guān)注~~~
