版本记录
版本号 | 时间 |
---|---|
V1.0 | 2020.02.17 星期一 |
前言
iOS中有关视图控件用户能看到的都在UIKit框架里面,用户交互也是通过UIKit进行的。感兴趣的参考上面几篇文章。
1. UIKit框架(一) —— UIKit动力学和移动效果(一)
2. UIKit框架(二) —— UIKit动力学和移动效果(二)
3. UIKit框架(三) —— UICollectionViewCell的扩张效果的实现(一)
4. UIKit框架(四) —— UICollectionViewCell的扩张效果的实现(二)
5. UIKit框架(五) —— 自定义控件:可重复使用的滑块(一)
6. UIKit框架(六) —— 自定义控件:可重复使用的滑块(二)
7. UIKit框架(七) —— 动态尺寸UITableViewCell的实现(一)
8. UIKit框架(八) —— 动态尺寸UITableViewCell的实现(二)
9. UIKit框架(九) —— UICollectionView的数据异步预加载(一)
10. UIKit框架(十) —— UICollectionView的数据异步预加载(二)
11. UIKit框架(十一) —— UICollectionView的重用、选择和重排序(一)
12. UIKit框架(十二) —— UICollectionView的重用、选择和重排序(二)
13. UIKit框架(十三) —— 如何创建自己的侧滑式面板导航(一)
14. UIKit框架(十四) —— 如何创建自己的侧滑式面板导航(二)
15. UIKit框架(十五) —— 基于自定义UICollectionViewLayout布局的简单示例(一)
16. UIKit框架(十六) —— 基于自定义UICollectionViewLayout布局的简单示例(二)
17. UIKit框架(十七) —— 基于自定义UICollectionViewLayout布局的简单示例(三)
18. UIKit框架(十八) —— 基于CALayer属性的一种3D边栏动画的实现(一)
19. UIKit框架(十九) —— 基于CALayer属性的一种3D边栏动画的实现(二)
20. UIKit框架(二十) —— 基于UILabel跑马灯类似效果的实现(一)
21. UIKit框架(二十一) —— UIStackView的使用(一)
22. UIKit框架(二十二) —— 基于UIPresentationController的自定义viewController的转场和展示(一)
23. UIKit框架(二十三) —— 基于UIPresentationController的自定义viewController的转场和展示(二)
24. UIKit框架(二十四) —— 基于UICollectionViews和Drag-Drop在两个APP间的使用示例 (一)
25. UIKit框架(二十五) —— 基于UICollectionViews和Drag-Drop在两个APP间的使用示例 (二)
26. UIKit框架(二十六) —— UICollectionView的自定义布局 (一)
27. UIKit框架(二十七) —— UICollectionView的自定义布局 (二)
28. UIKit框架(二十八) —— 一个UISplitViewController的简单实用示例 (一)
29. UIKit框架(二十九) —— 一个UISplitViewController的简单实用示例 (二)
30. UIKit框架(三十) —— 基于UICollectionViewCompositionalLayout API的UICollectionViews布局的简单示例(一)
31. UIKit框架(三十一) —— 基于UICollectionViewCompositionalLayout API的UICollectionViews布局的简单示例(二)
32. UIKit框架(三十二) —— 替换Peek and Pop交互的基于iOS13的Context Menus(一)
33. UIKit框架(三十三) —— 替换Peek and Pop交互的基于iOS13的Context Menus(二)
34. UIKit框架(三十四) —— Accessibility的使用(一)
源码
1. Swift
首先看下工程组织结构
下面看下sb中的内容
接着就是源码了
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的使用,感兴趣的给个赞或者关注~~~