LoginSignup
0
0

More than 5 years have passed since last update.

How to use associated object is swift

Last updated at Posted at 2018-09-17

How to create a loading view in UIView using extension

import UIKit
import ObjectiveC

extension UIView {

    private struct AssociatedKeys {
        static var LoadingDescriptiveName = "loading_nsh_DescriptiveName"
        static var LoadingViewDescriptiveName = "loading_view_nsh_DescriptiveName"
    }

    private func updateLoadingView(shouldShow: Bool) {
        if shouldShow {
            loadingView.startAnimating()
            addSubview(loadingView)
            loadingView.isHidden = false

            if let superview = loadingView.superview {
                loadingView.backgroundColor = superview.backgroundColor
                loadingView.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
                loadingView.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true

            }
        } else {
            UIView.transition(with: self,
                              duration: 0.35,
                              options: .transitionCrossDissolve,
                              animations: { [weak self] in
                                self?.loadingView.removeFromSuperview()
            }, completion: nil)
        }
    }

    @objc var loading: Bool {
        get {
            guard let isLoading = objc_getAssociatedObject(self, &AssociatedKeys.LoadingDescriptiveName) as? Bool else { return false }
            return isLoading
        }
        set {
            objc_setAssociatedObject(self,
                                     &AssociatedKeys.LoadingDescriptiveName,
                                     newValue,
                                     .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            updateLoadingView(shouldShow: newValue)
        }
    }


    private var loadingView: UIActivityIndicatorView {

        if let view = objc_getAssociatedObject(self, &AssociatedKeys.LoadingViewDescriptiveName) as? UIActivityIndicatorView {
            return view
        } else {
            let loadingView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
            loadingView.hidesWhenStopped = true
            loadingView.clipsToBounds = true
            loadingView.stopAnimating()
            loadingView.translatesAutoresizingMaskIntoConstraints = false
            objc_setAssociatedObject(self,
                                     &AssociatedKeys.LoadingViewDescriptiveName,
                                     loadingView,
                                     .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            return loadingView
        }
    }
} 

source:

d

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0