NCMainCommon.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. //
  2. // NCMainCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 18/07/18.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import TLPhotoPicker
  25. import ZIPFoundation
  26. import NCCommunication
  27. //MARK: - Main Common
  28. class NCMainCommon: NSObject {
  29. @objc static let shared: NCMainCommon = {
  30. let instance = NCMainCommon()
  31. instance.createImagesThemingColor()
  32. return instance
  33. }()
  34. var metadataEditPhoto: tableMetadata?
  35. //MARK: -
  36. struct NCMainCommonImages {
  37. static var cellSharedImage = UIImage()
  38. static var cellCanShareImage = UIImage()
  39. static var cellShareByLinkImage = UIImage()
  40. static var cellFavouriteImage = UIImage()
  41. static var cellMoreImage = UIImage()
  42. static var cellCommentImage = UIImage()
  43. static var cellLivePhotoImage = UIImage()
  44. static var cellFolderEncryptedImage = UIImage()
  45. static var cellFolderSharedWithMeImage = UIImage()
  46. static var cellFolderPublicImage = UIImage()
  47. static var cellFolderGroupImage = UIImage()
  48. static var cellFolderExternalImage = UIImage()
  49. static var cellFolderAutomaticUploadImage = UIImage()
  50. static var cellFolderImage = UIImage()
  51. static var cellPlayImage = UIImage()
  52. }
  53. @objc func createImagesThemingColor() {
  54. NCMainCommonImages.cellSharedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  55. NCMainCommonImages.cellCanShareImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  56. NCMainCommonImages.cellShareByLinkImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "sharebylink"), width: 100, height: 100, color: NCBrandColor.sharedInstance.optionItem)
  57. NCMainCommonImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  58. NCMainCommonImages.cellMoreImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.optionItem)
  59. NCMainCommonImages.cellCommentImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "comment"), width: 30, height: 30, color: NCBrandColor.sharedInstance.graySoft)
  60. NCMainCommonImages.cellLivePhotoImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: NCBrandColor.sharedInstance.textView)
  61. NCMainCommonImages.cellFolderEncryptedImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderEncrypted"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  62. NCMainCommonImages.cellFolderSharedWithMeImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_shared_with_me"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  63. NCMainCommonImages.cellFolderPublicImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_public"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  64. NCMainCommonImages.cellFolderGroupImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_group"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  65. NCMainCommonImages.cellFolderExternalImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder_external"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  66. NCMainCommonImages.cellFolderAutomaticUploadImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  67. NCMainCommonImages.cellFolderImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 600, height: 600, color: NCBrandColor.sharedInstance.brandElement)
  68. NCMainCommonImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  69. }
  70. //MARK: -
  71. @objc func triggerProgressTask(_ notification: Notification, sectionDataSourceocIdIndexPath: NSDictionary, tableView: UITableView, viewController: UIViewController, serverUrlViewController: String?) {
  72. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  73. if viewController.viewIfLoaded?.window == nil {
  74. return
  75. }
  76. guard let dic = notification.userInfo else {
  77. return
  78. }
  79. let _ = dic["account"] as? NSString ?? ""
  80. let ocId = dic["ocId"] as? NSString ?? ""
  81. let serverUrl = dic["serverUrl"] as? String ?? ""
  82. let status = dic["status"] as? Int ?? Int(k_metadataStatusNormal)
  83. let progress = dic["progress"] as? CGFloat ?? 0
  84. let totalBytes = dic["totalBytes"] as? Double ?? 0
  85. let totalBytesExpected = dic["totalBytesExpected"] as? Double ?? 0
  86. if serverUrlViewController != nil && serverUrlViewController! != serverUrl {
  87. return
  88. }
  89. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: ocId)
  90. guard let indexPath = sectionDataSourceocIdIndexPath.object(forKey: ocId) else {
  91. return
  92. }
  93. if isValidIndexPath(indexPath as! IndexPath, view: tableView) {
  94. if let cell = tableView.cellForRow(at: indexPath as! IndexPath) as? CCCellMainTransfer {
  95. var image = ""
  96. if status == k_metadataStatusInDownload {
  97. image = "↓"
  98. } else if status == k_metadataStatusInUpload {
  99. image = "↑"
  100. }
  101. cell.labelInfoFile?.text = CCUtility.transformedSize(totalBytesExpected) + " - " + image + CCUtility.transformedSize(totalBytes)
  102. cell.transferButton?.progress = progress
  103. }
  104. }
  105. }
  106. //MARK: -
  107. @objc func cellForRowAtIndexPath(_ indexPath: IndexPath, tableView: UITableView ,metadata: tableMetadata, metadataFolder: tableMetadata?, serverUrl: String, autoUploadFileName: String, autoUploadDirectory: String, tableShare: tableShare?, livePhoto: Bool) -> UITableViewCell {
  108. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  109. // Create File System
  110. if metadata.directory {
  111. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId)
  112. } else {
  113. CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  114. }
  115. // CCCell
  116. if metadata.status == k_metadataStatusNormal || metadata.status == k_metadataStatusDownloadError {
  117. // NORMAL
  118. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMain", for: indexPath) as! CCCellMain
  119. cell.labelTitle.text = metadata.fileNameView
  120. cell.filePreviewImageView.image = nil
  121. cell.filePreviewImageView.backgroundColor = UIColor.lightGray
  122. // Download preview
  123. if !(metadataFolder?.e2eEncrypted ?? false) {
  124. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: tableView, indexPath: indexPath)
  125. }
  126. // Share
  127. var isShare = false
  128. var isMounted = false
  129. if metadataFolder != nil {
  130. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  131. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  132. }
  133. if metadata.directory {
  134. // lable Info
  135. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date)
  136. cell.file.backgroundColor = nil
  137. // File Image & Image Title Segue
  138. if metadata.e2eEncrypted {
  139. cell.file.image = NCMainCommonImages.cellFolderEncryptedImage
  140. } else if isShare {
  141. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  142. } else if (tableShare != nil && tableShare!.shareType != 3) {
  143. cell.file.image = NCMainCommonImages.cellFolderSharedWithMeImage
  144. } else if (tableShare != nil && tableShare!.shareType == 3) {
  145. cell.file.image = NCMainCommonImages.cellFolderPublicImage
  146. } else if metadata.mountType == "group" {
  147. cell.file.image = NCMainCommonImages.cellFolderGroupImage
  148. } else if isMounted {
  149. cell.file.image = NCMainCommonImages.cellFolderExternalImage
  150. } else if metadata.fileName == autoUploadFileName && serverUrl == autoUploadDirectory {
  151. cell.file.image = NCMainCommonImages.cellFolderAutomaticUploadImage
  152. } else {
  153. cell.file.image = NCMainCommonImages.cellFolderImage
  154. }
  155. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  156. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  157. // Local image: offline
  158. if tableDirectory != nil && tableDirectory!.offline {
  159. cell.local.image = UIImage.init(named: "offlineFlag")
  160. }
  161. } else {
  162. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  163. // Lable Info
  164. cell.labelInfoFile.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  165. // File Image
  166. if iconFileExists {
  167. cell.file.backgroundColor = nil
  168. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  169. } else if(!metadata.hasPreview){
  170. cell.file.backgroundColor = nil
  171. if metadata.iconName.count > 0 {
  172. cell.file.image = UIImage.init(named: metadata.iconName)
  173. } else {
  174. cell.file.image = UIImage.init(named: "file")
  175. }
  176. }
  177. // Local Image - Offline
  178. let size = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  179. if size > 0 {
  180. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  181. if tableLocalFile == nil && size == metadata.size {
  182. NCManageDatabase.sharedInstance.addLocalFile(metadata: metadata)
  183. }
  184. if tableLocalFile != nil && tableLocalFile!.offline { cell.local.image = UIImage.init(named: "offlineFlag") }
  185. else { cell.local.image = UIImage.init(named: "local") }
  186. }
  187. // Status image: encrypted
  188. let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND fileNameIdentifier == %@", appDelegate.account, metadata.fileName))
  189. if tableE2eEncryption != nil && NCUtility.shared.isEncryptedMetadata(metadata) {
  190. cell.status.image = UIImage.init(named: "encrypted")
  191. }
  192. // Live Photo
  193. if metadata.livePhoto && livePhoto {
  194. cell.status.image = NCMainCommonImages.cellLivePhotoImage
  195. }
  196. }
  197. //
  198. // File & Directory
  199. //
  200. // Favorite
  201. if metadata.favorite {
  202. cell.favorite.image = NCMainCommonImages.cellFavouriteImage
  203. }
  204. // Share image
  205. if !(metadataFolder?.e2eEncrypted ?? false) && !metadata.e2eEncrypted {
  206. if (isShare) {
  207. cell.shared.image = NCMainCommonImages.cellSharedImage
  208. } else if (tableShare != nil && tableShare!.shareType == 3) {
  209. cell.shared.image = NCMainCommonImages.cellShareByLinkImage
  210. } else if (tableShare != nil && tableShare!.shareType != 3) {
  211. cell.shared.image = NCMainCommonImages.cellSharedImage
  212. } else {
  213. cell.shared.image = NCMainCommonImages.cellCanShareImage
  214. }
  215. if metadata.ownerId != appDelegate.userID {
  216. // Load avatar
  217. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  218. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  219. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  220. if let avatar = UIImage(contentsOfFile: fileNameSourceAvatar) {
  221. cell.shared.image = avatar
  222. }
  223. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  224. if let avatar = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar) {
  225. cell.shared.image = avatar
  226. }
  227. } else {
  228. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  229. if errorCode == 0 && account == appDelegate.account {
  230. cell.shared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  231. }
  232. }
  233. }
  234. }
  235. }
  236. // Comment
  237. if metadata.commentsUnread {
  238. cell.comment.image = NCMainCommonImages.cellCommentImage
  239. cell.labelTitleTrailingConstraint.constant = 160
  240. } else {
  241. cell.labelTitleTrailingConstraint.constant = 110
  242. }
  243. // More Image
  244. cell.more.image = NCMainCommonImages.cellMoreImage
  245. // downloadFile Error
  246. if metadata.status == k_metadataStatusDownloadError {
  247. cell.status.image = UIImage.init(named: "statuserror")
  248. if metadata.sessionError.count == 0 {
  249. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_downloaded_", comment: "")
  250. } else {
  251. cell.labelInfoFile.text = metadata.sessionError
  252. }
  253. }
  254. return cell
  255. } else {
  256. // TRASNFER
  257. let cell = tableView.dequeueReusableCell(withIdentifier: "CellMainTransfer", for: indexPath) as! CCCellMainTransfer
  258. cell.labelTitle.text = metadata.fileNameView
  259. var progress: CGFloat = 0.0
  260. var totalBytes: Double = 0.0
  261. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  262. if progressArray != nil && progressArray?.count == 3 {
  263. progress = progressArray?.object(at: 0) as? CGFloat ?? 0
  264. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  265. }
  266. // Write status on Label Info
  267. switch metadata.status {
  268. case Int(k_metadataStatusWaitDownload):
  269. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  270. progress = 0.0
  271. break
  272. case Int(k_metadataStatusInDownload):
  273. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  274. progress = 0.0
  275. break
  276. case Int(k_metadataStatusDownloading):
  277. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↓" + CCUtility.transformedSize(totalBytes)
  278. break
  279. case Int(k_metadataStatusWaitUpload):
  280. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  281. progress = 0.0
  282. break
  283. case Int(k_metadataStatusInUpload):
  284. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  285. progress = 0.0
  286. break
  287. case Int(k_metadataStatusUploading):
  288. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size) + " - ↑" + CCUtility.transformedSize(totalBytes)
  289. break
  290. default:
  291. cell.labelInfoFile.text = CCUtility.transformedSize(metadata.size)
  292. progress = 0.0
  293. }
  294. let iconFileExists = FileManager.default.fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  295. if iconFileExists {
  296. cell.file.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  297. } else {
  298. if metadata.status == k_metadataStatusWaitUpload || metadata.status == k_metadataStatusInUpload || metadata.status == k_metadataStatusUploading || metadata.status == k_metadataStatusUploadError {
  299. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudUpload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  300. } else {
  301. cell.file.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "cloudDownload"), width: 100, height: 100, color: NCBrandColor.sharedInstance.brandElement)
  302. }
  303. }
  304. // uploadFileError
  305. if metadata.status == k_metadataStatusUploadError {
  306. cell.status.image = UIImage.init(named: "statuserror")
  307. if metadata.sessionError.count == 0 {
  308. cell.labelInfoFile.text = NSLocalizedString("_error_", comment: "") + ", " + NSLocalizedString("_file_not_uploaded_", comment: "")
  309. } else {
  310. cell.labelInfoFile.text = metadata.sessionError
  311. }
  312. }
  313. // Progress
  314. cell.transferButton.progress = progress
  315. // User
  316. if metadata.account != appDelegate.account {
  317. let tableAccount = NCManageDatabase.sharedInstance.getAccount(predicate: NSPredicate(format: "account == %@", metadata.account))
  318. if tableAccount != nil {
  319. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + appDelegate.user + ".png"
  320. var avatar = UIImage.init(contentsOfFile: fileNamePath)
  321. if avatar != nil {
  322. let avatarImageView = CCAvatar.init(image: avatar, borderColor: UIColor.black, borderWidth: 0.5)
  323. let imageSize = avatarImageView?.bounds.size
  324. UIGraphicsBeginImageContext(imageSize!)
  325. let context = UIGraphicsGetCurrentContext()
  326. avatarImageView?.layer.render(in: context!)
  327. avatar = UIGraphicsGetImageFromCurrentImageContext()
  328. UIGraphicsEndImageContext()
  329. cell.user.image = avatar
  330. }
  331. }
  332. }
  333. return cell
  334. }
  335. }
  336. @objc func getMetadataFromSectionDataSourceIndexPath(_ indexPath: IndexPath?, sectionDataSource: CCSectionDataSourceMetadata?) -> tableMetadata? {
  337. guard let indexPath = indexPath else {
  338. return nil
  339. }
  340. guard let sectionDataSource = sectionDataSource else {
  341. return nil
  342. }
  343. let section = indexPath.section + 1
  344. let row = indexPath.row + 1
  345. let totSections = sectionDataSource.sections.count
  346. if totSections < section || section > totSections {
  347. return nil
  348. }
  349. let valueSection = sectionDataSource.sections.object(at: indexPath.section)
  350. guard let filesID = sectionDataSource.sectionArrayRow.object(forKey: valueSection) as? NSArray else {
  351. return nil
  352. }
  353. let totRows = filesID.count
  354. if totRows < row || row > totRows {
  355. return nil
  356. }
  357. let ocId = filesID.object(at: indexPath.row)
  358. let metadata = sectionDataSource.allRecordsDataSource.object(forKey: ocId) as? tableMetadata
  359. return metadata
  360. }
  361. @objc func isValidIndexPath(_ indexPath: IndexPath, view: Any) -> Bool {
  362. if view is UICollectionView {
  363. return indexPath.section < (view as! UICollectionView).numberOfSections && indexPath.row < (view as! UICollectionView).numberOfItems(inSection: indexPath.section)
  364. }
  365. if view is UITableView {
  366. return indexPath.section < (view as! UITableView).numberOfSections && indexPath.row < (view as! UITableView).numberOfRows(inSection: indexPath.section)
  367. }
  368. return true
  369. }
  370. }
  371. //MARK: - Main TabBarController
  372. class CCMainTabBarController : UITabBarController, UITabBarControllerDelegate {
  373. override func viewDidLoad() {
  374. super.viewDidLoad()
  375. delegate = self
  376. }
  377. //Delegate methods
  378. func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
  379. let tabViewControllers = tabBarController.viewControllers!
  380. guard let toIndex = tabViewControllers.firstIndex(of: viewController) else {
  381. if let vc = viewController as? UINavigationController {
  382. vc.popToRootViewController(animated: true);
  383. }
  384. return false
  385. }
  386. animateToTab(toIndex: toIndex)
  387. return true
  388. }
  389. func animateToTab(toIndex: Int) {
  390. let tabViewControllers = viewControllers!
  391. let fromView = selectedViewController!.view!
  392. let toView = tabViewControllers[toIndex].view!
  393. let fromIndex = tabViewControllers.firstIndex(of: selectedViewController!)
  394. guard fromIndex != toIndex else {return}
  395. // Add the toView to the tab bar view
  396. fromView.superview?.addSubview(toView)
  397. fromView.superview?.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  398. // Position toView off screen (to the left/right of fromView)
  399. let screenWidth = UIScreen.main.bounds.size.width;
  400. let scrollRight = toIndex > fromIndex!;
  401. let offset = (scrollRight ? screenWidth : -screenWidth)
  402. toView.center = CGPoint(x: (fromView.center.x) + offset, y: (toView.center.y))
  403. // Disable interaction during animation
  404. view.isUserInteractionEnabled = false
  405. UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  406. // Slide the views by -offset
  407. fromView.center = CGPoint(x: fromView.center.x - offset, y: fromView.center.y);
  408. toView.center = CGPoint(x: toView.center.x - offset, y: toView.center.y);
  409. }, completion: { finished in
  410. // Remove the old view from the tabbar view.
  411. fromView.removeFromSuperview()
  412. self.selectedIndex = toIndex
  413. self.view.isUserInteractionEnabled = true
  414. })
  415. }
  416. }