Swift懶加載 惰性載入 lazy

1. 什麼是懶加載?

懶加載也稱惰性載入(英語:lazy loading、infinite scroll,又稱延遲載入、懶載入、無限捲動、瀑布流),是一種設計模式
當訪問一個頁面的時候,先把imageView, Label或是其他元件,畫面未出現前不先預先加載,畫面顯示後再去呼叫,並且之後重複呼叫就不用在宣告,可以直接拿來以前宣告過得來使用。

2. 為什麼要使用懶加載?

很多頁面,內容很豐富,頁面很長加上畫面複雜。
元件太多要顯示,就可以使用懶加仔,當有顯示的時候再去呼叫,加快使用者體驗,增加程式效率。
預先加載會導致網頁或是APP過慢問題。

Swift懶加載範例

UIView

lazy var topView: UIView = {
    let topView = UIView()
    topView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 48 + kSafeTopPadding)
    topView.backgroundColor = UIColor.init(red: 46.0/255.0, green: 144.0/255.0, blue: 133.0/255.0, alpha: 1.0)
    return topView
}()

UILabel

lazy var titleLabel: UILabel = {
    let titleLabel = UILabel()
    titleLabel.frame = CGRect(x: topView.center.x - kScreenWidth * 0.66 / 2, y: kSafeTopPadding, width: self.frame.width * 0.66, height: self.topView.frame.height - kSafeTopPadding)
    titleLabel.text = "我的邀請碼"
    titleLabel.textColor = .white
    titleLabel.textAlignment = .center
    titleLabel.font = UIFont(name:"PingFangTC-Semibold", size: 20.0)
    return titleLabel
}()

UIButton

lazy var friendInviteButton: UIButton = {
    let friendInviteButton = UIButton()
    friendInviteButton.setTitle("好友邀請紀錄", for: .normal)
    friendInviteButton.titleLabel?.font = UIFont(name: "PingFangTC-Semibold", size: 16)
    friendInviteButton.setTitleColor(UIColor.init(red: 128/255, green: 128/255, blue: 128/255, alpha: 1), for: .normal)
    friendInviteButton.setTitleColor(UIColor.init(red: 71/255, green: 171/255, blue: 161/255, alpha: 1), for: .selected)
    friendInviteButton.backgroundColor = UIColor.white
    friendInviteButton.isSelected = false
    friendInviteButton.addTarget(self, action: #selector(friendInviteButtonPress(sender:)), for: .touchUpInside)
    friendInviteButton.setImage(UIImage.init(named: "notice"), for: .normal)
    friendInviteButton.imageView?.contentMode = .scaleAspectFit
    return friendInviteButton
}()

UIStackView

lazy var topStackView: UIStackView = {
    let topStackView = UIStackView(arrangedSubviews: [friendRewardButton, friendInviteButton])
    topStackView.frame = CGRect.init(x: 0, y: topView.frame.maxY, width: self.frame.width, height: kRealHeightValue(value: 50))
    topStackView.axis = .horizontal
    topStackView.distribution = .fillEqually
    topStackView.spacing = 0.0
    return topStackView
}()

UIPageViewController

lazy var pageViewControl: UIPageViewController = {
    let pageViewControl = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    pageViewControl.view.frame = CGRect.init(x: 0, y: buttonBar.frame.maxY, width: self.frame.width, height: self.frame.height - buttonBar.frame.maxY)
    pageViewControl.isEditing = false
    return pageViewControl
}()

UIPageControl

lazy var pageView: UIPageControl = {
    let pageView = UIPageControl()
    pageView.frame = CGRect(x: 0, y: sliderCollectionView.frame.maxY - 20, width: 100, height: 20)
    pageView.backgroundColor = UIColor.clear
    pageView.currentPageIndicatorTintColor = UIColor.init(displayP3Red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    pageView.pageIndicatorTintColor = UIColor.init(displayP3Red: 1.0, green: 1.0, blue: 1.0, alpha: 0.2)
    pageView.numberOfPages = 2
    pageView.currentPage = 0
    return pageView
}()

UIImageView

lazy var inviteImageView: UIImageView = {
    let inviteImageView = UIImageView()
    inviteImageView.frame = CGRect(x: 0, y: subTitleLabel.frame.maxY + kRealHeightValue(value: 21),width: kRealHeightValue(value: 230), height: kRealHeightValue(value: 230))
    inviteImageView.center.x = self.center.x
    inviteImageView.image = UIImage.init(named: "bg_code")
    inviteImageView.contentMode = .scaleAspectFit
    return inviteImageView
}()

UICollectionView

lazy var sliderCollectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    layout.minimumLineSpacing = 5
    layout.scrollDirection = .horizontal
    let sliderCollectionView = UICollectionView(frame: CGRect(x: kRealValue(value: 17), y: topView.frame.maxY + kRealHeightValue(value: 10), width: kScreenWidth - kRealValue(value: 17) * 2, height: (kScreenWidth - kRealValue(value: 17) * 2) * 480/1080 ),collectionViewLayout: layout)
    sliderCollectionView.backgroundColor = UIColor.white
    sliderCollectionView.layer.cornerRadius = 10
    sliderCollectionView.register(UINib(nibName:"BannerImageCell", bundle:nil),
                                  forCellWithReuseIdentifier:"BannerImageCell")
    sliderCollectionView.delegate = self
    sliderCollectionView.dataSource = self
    sliderCollectionView.isPagingEnabled = true
    sliderCollectionView.collectionViewLayout.invalidateLayout()
    return sliderCollectionView
}()

UITableView

lazy var tableView: UITableView = {
    let tableView = UITableView()
    tableView.frame = CGRect(x: kRealValue(value: 17), y:  kRealHeightValue(value: 27), width: kScreenWidth - kRealValue(value: 17)*2, height: self.frame.height - kRealHeightValue(value: 27) - bottomView.frame.height)
    tableView.backgroundColor = .clear
    tableView.separatorStyle = .none
    tableView.register(UINib(nibName:"RepaymentPageCell", bundle:nil),
                       forCellReuseIdentifier:"RepaymentPageCell")
    return tableView
}()

UITextField

lazy var allAmountTextField: UITextField = {
    let allAmountTextField = UITextField()
    allAmountTextField.addBottomBorder()
    allAmountTextField.textAlignment = .center
    allAmountTextField.keyboardType = .numberPad
    return allAmountTextField
}()

UITextView

lazy var contentTextView: UITextView = {
    let contentTextView = UITextView()
    contentTextView.frame = CGRect.init(x: kRealValue(value: 45), y: dateLabel.frame.maxY + kRealHeightValue(value: 16.0), width: detailView.frame.width - kRealValue(value: 45) * 2, height: detailView.frame.height - dateLabel.frame.maxY - kRealHeightValue(value: 16.0))
    contentTextView.textColor = UIColor.init(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
    contentTextView.font = UIFont.systemFont(ofSize: 14)
    contentTextView.textContainer.lineFragmentPadding = 0
    contentTextView.textContainerInset = .zero
    contentTextView.isEditable = false
    contentTextView.text = ""
    return contentTextView
}()

UISegmentedControl

lazy var segmentedControl: UISegmentedControl = {
    let segmentedControl = UISegmentedControl(items: ["還款頁面","還款明細"])
    segmentedControl.backgroundColor = .clear
    if #available(iOS 13.0, *) {
        segmentedControl.selectedSegmentTintColor = .clear
    } else {
        // Fallback on earlier versions
    }

    segmentedControl.tintColor = .clear
    segmentedControl.backgroundColor = .white
    segmentedControl.frame = CGRect.init(x: 0, y: topView.frame.maxY, width: self.view.frame.width, height: kRealHeightValue(value: 50))
    segmentedControl.addTarget(self, action: #selector(segmentedChange), for: .valueChanged)
    segmentedControl.setTitleTextAttributes([
        NSAttributedString.Key.font: UIFont(name: "PingFangTC-Regular", size: 16)!,
        NSAttributedString.Key.foregroundColor: UIColor.init(red: 43.0/255.0, green: 42.0/255.0, blue: 47.0/255.0, alpha: 1.0)
    ], for: .normal)

    segmentedControl.setTitleTextAttributes([
        NSAttributedString.Key.font : UIFont(name: "PingFangTC-Semibold", size: 16)!,
        NSAttributedString.Key.foregroundColor: UIColor.init(red: 71/255, green: 171/255, blue: 161/255, alpha: 1)
    ], for: .selected)
    return segmentedControl
}()

UIScrollView

lazy var scrollView: UIScrollView = {
    var scrollView = UIScrollView()
    scrollView = UIScrollView(frame: self.frame)
    scrollView.scrollsToTop = false
    scrollView.isDirectionalLockEnabled = false
    scrollView.contentSize = CGSize(width: self.frame.width, height: kRealHeightValue(value: 832))
    return scrollView
}()

保留席位

UIView

UIView

參考網站:
懒加载和预加载
惰性載入


Swift懶加載

Swift更多文章

Swift 彈出視窗 AlertController 的使用方法 💥

Swift 判斷螢幕方向 📱

Swift Core Data 實現 💾🔥

Swift UISegmentedControl 💻分段控制器!

Swift 實現抽屜效果 🧹

Categorized in: