UIButton+Kingfisher.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //
  2. // UIButton+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/13.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if !os(watchOS)
  27. #if canImport(UIKit)
  28. import UIKit
  29. @MainActor
  30. extension KingfisherWrapper where Base: UIButton {
  31. // MARK: Setting Image
  32. /// Sets an image to the button for a specified state with a source.
  33. ///
  34. /// - Parameters:
  35. /// - source: The `Source` object contains information about the image.
  36. /// - state: The button state to which the image should be set.
  37. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  38. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  39. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  40. /// `expectedContentLength`, this block will not be called.
  41. /// - completionHandler: Called when the image retrieved and set finished.
  42. /// - Returns: A task represents the image downloading.
  43. ///
  44. /// - Note:
  45. /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache
  46. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  47. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  48. ///
  49. @discardableResult
  50. public func setImage(
  51. with source: Source?,
  52. for state: UIControl.State,
  53. placeholder: UIImage? = nil,
  54. options: KingfisherOptionsInfo? = nil,
  55. progressBlock: DownloadProgressBlock? = nil,
  56. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  57. {
  58. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  59. return setImage(
  60. with: source,
  61. for: state,
  62. placeholder: placeholder,
  63. parsedOptions: options,
  64. progressBlock: progressBlock,
  65. completionHandler: completionHandler
  66. )
  67. }
  68. /// Sets an image to the button for a specified state with a requested resource.
  69. ///
  70. /// - Parameters:
  71. /// - resource: The `Resource` object contains information about the resource.
  72. /// - state: The button state to which the image should be set.
  73. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  74. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  75. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  76. /// `expectedContentLength`, this block will not be called.
  77. /// - completionHandler: Called when the image retrieved and set finished.
  78. /// - Returns: A task represents the image downloading.
  79. ///
  80. /// - Note:
  81. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  82. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  83. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  84. ///
  85. @discardableResult
  86. public func setImage(
  87. with resource: (any Resource)?,
  88. for state: UIControl.State,
  89. placeholder: UIImage? = nil,
  90. options: KingfisherOptionsInfo? = nil,
  91. progressBlock: DownloadProgressBlock? = nil,
  92. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  93. {
  94. return setImage(
  95. with: resource?.convertToSource(),
  96. for: state,
  97. placeholder: placeholder,
  98. options: options,
  99. progressBlock: progressBlock,
  100. completionHandler: completionHandler)
  101. }
  102. @discardableResult
  103. public func setImage(
  104. with source: Source?,
  105. for state: UIControl.State,
  106. placeholder: UIImage? = nil,
  107. parsedOptions: KingfisherParsedOptionsInfo,
  108. progressBlock: DownloadProgressBlock? = nil,
  109. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  110. {
  111. var mutatingSelf = self
  112. return setImage(
  113. with: source,
  114. imageAccessor: ImagePropertyAccessor(
  115. setImage: { image, _ in base.setImage(image, for: state) },
  116. getImage: { base.image(for: state) }
  117. ),
  118. taskAccessor: TaskPropertyAccessor(
  119. setTaskIdentifier: { setTaskIdentifier($0, for: state) },
  120. getTaskIdentifier: { taskIdentifier(for: state) },
  121. setTask: { mutatingSelf.imageTask = $0 }
  122. ),
  123. placeholder: placeholder,
  124. parsedOptions: parsedOptions,
  125. progressBlock: progressBlock,
  126. completionHandler: completionHandler
  127. )
  128. }
  129. // MARK: Cancelling Downloading Task
  130. /// Cancels the image download task of the button if it is running.
  131. /// Nothing will happen if the downloading has already finished.
  132. public func cancelImageDownloadTask() {
  133. imageTask?.cancel()
  134. }
  135. // MARK: Setting Background Image
  136. /// Sets a background image to the button for a specified state with a source.
  137. ///
  138. /// - Parameters:
  139. /// - source: The `Source` object contains information about the image.
  140. /// - state: The button state to which the image should be set.
  141. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  142. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  143. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  144. /// `expectedContentLength`, this block will not be called.
  145. /// - completionHandler: Called when the image retrieved and set finished.
  146. /// - Returns: A task represents the image downloading.
  147. ///
  148. /// - Note:
  149. /// Internally, this method will use `KingfisherManager` to get the requested source
  150. /// Since this method will perform UI changes, you must call it from the main thread.
  151. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  152. ///
  153. @discardableResult
  154. public func setBackgroundImage(
  155. with source: Source?,
  156. for state: UIControl.State,
  157. placeholder: UIImage? = nil,
  158. options: KingfisherOptionsInfo? = nil,
  159. progressBlock: DownloadProgressBlock? = nil,
  160. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  161. {
  162. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  163. return setBackgroundImage(
  164. with: source,
  165. for: state,
  166. placeholder: placeholder,
  167. parsedOptions: options,
  168. progressBlock: progressBlock,
  169. completionHandler: completionHandler
  170. )
  171. }
  172. /// Sets a background image to the button for a specified state with a requested resource.
  173. ///
  174. /// - Parameters:
  175. /// - resource: The `Resource` object contains information about the resource.
  176. /// - state: The button state to which the image should be set.
  177. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  178. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  179. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  180. /// `expectedContentLength`, this block will not be called.
  181. /// - completionHandler: Called when the image retrieved and set finished.
  182. /// - Returns: A task represents the image downloading.
  183. ///
  184. /// - Note:
  185. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  186. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  187. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  188. ///
  189. @discardableResult
  190. public func setBackgroundImage(
  191. with resource: (any Resource)?,
  192. for state: UIControl.State,
  193. placeholder: UIImage? = nil,
  194. options: KingfisherOptionsInfo? = nil,
  195. progressBlock: DownloadProgressBlock? = nil,
  196. completionHandler: (@Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  197. {
  198. return setBackgroundImage(
  199. with: resource?.convertToSource(),
  200. for: state,
  201. placeholder: placeholder,
  202. options: options,
  203. progressBlock: progressBlock,
  204. completionHandler: completionHandler)
  205. }
  206. func setBackgroundImage(
  207. with source: Source?,
  208. for state: UIControl.State,
  209. placeholder: UIImage? = nil,
  210. parsedOptions: KingfisherParsedOptionsInfo,
  211. progressBlock: DownloadProgressBlock? = nil,
  212. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  213. {
  214. var mutatingSelf = self
  215. return setImage(
  216. with: source,
  217. imageAccessor: ImagePropertyAccessor(
  218. setImage: { image, _ in
  219. base.setBackgroundImage(image, for: state)
  220. },
  221. getImage: {
  222. base.backgroundImage(for: state)
  223. }
  224. ),
  225. taskAccessor: TaskPropertyAccessor(
  226. setTaskIdentifier: { setBackgroundTaskIdentifier($0, for: state) },
  227. getTaskIdentifier: { backgroundTaskIdentifier(for: state) },
  228. setTask: { mutatingSelf.backgroundImageTask = $0 }
  229. ),
  230. placeholder: placeholder,
  231. parsedOptions: parsedOptions,
  232. progressBlock: progressBlock,
  233. completionHandler: completionHandler
  234. )
  235. }
  236. // MARK: Cancelling Background Downloading Task
  237. /// Cancels the background image download task of the button if it is running.
  238. /// Nothing will happen if the downloading has already finished.
  239. public func cancelBackgroundImageDownloadTask() {
  240. backgroundImageTask?.cancel()
  241. }
  242. }
  243. // MARK: - Associated Object
  244. @MainActor private var taskIdentifierKey: Void?
  245. @MainActor private var imageTaskKey: Void?
  246. // MARK: Properties
  247. @MainActor
  248. extension KingfisherWrapper where Base: UIButton {
  249. private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]>
  250. public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
  251. return taskIdentifierInfo.value[state.rawValue]
  252. }
  253. private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
  254. taskIdentifierInfo.value[state.rawValue] = identifier
  255. }
  256. private var taskIdentifierInfo: TaskIdentifier {
  257. return getAssociatedObject(base, &taskIdentifierKey) ?? {
  258. setRetainedAssociatedObject(base, &taskIdentifierKey, $0)
  259. return $0
  260. } (TaskIdentifier([:]))
  261. }
  262. private var imageTask: DownloadTask? {
  263. get { return getAssociatedObject(base, &imageTaskKey) }
  264. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  265. }
  266. }
  267. @MainActor private var backgroundTaskIdentifierKey: Void?
  268. @MainActor private var backgroundImageTaskKey: Void?
  269. // MARK: Background Properties
  270. @MainActor
  271. extension KingfisherWrapper where Base: UIButton {
  272. public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
  273. return backgroundTaskIdentifierInfo.value[state.rawValue]
  274. }
  275. private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
  276. backgroundTaskIdentifierInfo.value[state.rawValue] = identifier
  277. }
  278. private var backgroundTaskIdentifierInfo: TaskIdentifier {
  279. return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? {
  280. setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0)
  281. return $0
  282. } (TaskIdentifier([:]))
  283. }
  284. private var backgroundImageTask: DownloadTask? {
  285. get { return getAssociatedObject(base, &backgroundImageTaskKey) }
  286. mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) }
  287. }
  288. }
  289. #endif
  290. #endif