南鑫林 před 5 roky
rodič
revize
ecc513bcd4
14 změnil soubory, kde provedl 543 přidání a 264 odebrání
  1. 15 7
      RainbowPlanet/RainbowPlanet.xcodeproj/project.pbxproj
  2. 1 0
      RainbowPlanet/RainbowPlanet/Modules/CommunityModule/CommunityFeaturedTopics/ViewController/CommunityFeaturedTopicsViewController.swift
  3. 49 37
      RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchContentList/View/SearchContentListCollectionCell.swift
  4. 78 13
      RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchContentList/ViewController/SearchContentListViewController.swift
  5. 15 0
      RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchResult/ViewController/SearchResultViewController.swift
  6. 7 1
      RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchTopicList/View/SearchTopicListTableViewCell.swift
  7. 48 3
      RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchTopicList/ViewController/SearchTopicListViewController.swift
  8. 1 1
      RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchUser/ViewController/SearchUserListViewController.swift
  9. 63 0
      RainbowPlanet/RainbowPlanet/Service/Model/CommunityModel/CommunityPostsModel.swift
  10. 53 0
      RainbowPlanet/RainbowPlanet/Service/Model/CommunityModel/CommunityTopicsModel.swift
  11. 42 3
      RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceApi/SwiftMoyaServiceCommunity/SwiftMoyaNetWorkServiceCommunity.swift
  12. 34 4
      RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceApi/SwiftMoyaServiceCommunity/SwiftMoyaServiceCommunityApi.swift
  13. 23 29
      RainbowPlanet/RainbowPlanet/Tools/WaterFallLayout/WaterFallLayout.h
  14. 114 166
      RainbowPlanet/RainbowPlanet/Tools/WaterFallLayout/WaterFallLayout.m

+ 15 - 7
RainbowPlanet/RainbowPlanet.xcodeproj/project.pbxproj

@@ -82,6 +82,9 @@
 		A72623DB22C2FC3C00AEF875 /* MessageHomeTwoCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = A72623DA22C2FC3C00AEF875 /* MessageHomeTwoCollectionViewCell.swift */; };
 		A72623E522C39C7000AEF875 /* FMLinkLabel.m in Sources */ = {isa = PBXBuildFile; fileRef = A72623E422C39C6F00AEF875 /* FMLinkLabel.m */; };
 		A72623E722C469B700AEF875 /* SearchMemberListModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A72623E622C469B600AEF875 /* SearchMemberListModel.swift */; };
+		A72623E922C4AFF200AEF875 /* CommunityTopicsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A72623E822C4AFF200AEF875 /* CommunityTopicsModel.swift */; };
+		A72623EB22C4B91900AEF875 /* CommunityPostsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A72623EA22C4B91900AEF875 /* CommunityPostsModel.swift */; };
+		A72623EE22C4CFD800AEF875 /* WaterFallLayout.m in Sources */ = {isa = PBXBuildFile; fileRef = A72623EC22C4CFD700AEF875 /* WaterFallLayout.m */; };
 		A7274C50228EE5F0000E3A07 /* PhotoAndCameraManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7274C4F228EE5EF000E3A07 /* PhotoAndCameraManager.swift */; };
 		A7274C59228EE636000E3A07 /* LBXScanNetAnimation.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7274C52228EE635000E3A07 /* LBXScanNetAnimation.swift */; };
 		A7274C5A228EE636000E3A07 /* LBXScanView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7274C53228EE635000E3A07 /* LBXScanView.swift */; };
@@ -342,7 +345,6 @@
 		A7D5F23322BB9BE600F8E9AF /* H5CommonViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F23222BB9BE600F8E9AF /* H5CommonViewController.swift */; };
 		A7D5F24D22BC720000F8E9AF /* WVJBModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F24C22BC720000F8E9AF /* WVJBModel.swift */; };
 		A7D5F25022BC7B3700F8E9AF /* WebViewJavascriptBridgeManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F24F22BC7B3700F8E9AF /* WebViewJavascriptBridgeManager.swift */; };
-		A7D5F25522BF8E6B00F8E9AF /* WaterFallLayout.m in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F25422BF8E6A00F8E9AF /* WaterFallLayout.m */; };
 		A7D5F25722C05BE900F8E9AF /* UserDetailModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F25622C05BE900F8E9AF /* UserDetailModel.swift */; };
 		A7D5F25A22C05D1400F8E9AF /* SwiftMoyaServiceCommunityApi.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F25922C05D1400F8E9AF /* SwiftMoyaServiceCommunityApi.swift */; };
 		A7D5F25C22C05E0800F8E9AF /* SwiftMoyaNetWorkServiceCommunity.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7D5F25B22C05E0800F8E9AF /* SwiftMoyaNetWorkServiceCommunity.swift */; };
@@ -643,6 +645,10 @@
 		A72623E322C39C6F00AEF875 /* FMLinkLabel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMLinkLabel.h; sourceTree = "<group>"; };
 		A72623E422C39C6F00AEF875 /* FMLinkLabel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMLinkLabel.m; sourceTree = "<group>"; };
 		A72623E622C469B600AEF875 /* SearchMemberListModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SearchMemberListModel.swift; sourceTree = "<group>"; };
+		A72623E822C4AFF200AEF875 /* CommunityTopicsModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommunityTopicsModel.swift; sourceTree = "<group>"; };
+		A72623EA22C4B91900AEF875 /* CommunityPostsModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommunityPostsModel.swift; sourceTree = "<group>"; };
+		A72623EC22C4CFD700AEF875 /* WaterFallLayout.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WaterFallLayout.m; sourceTree = "<group>"; };
+		A72623ED22C4CFD800AEF875 /* WaterFallLayout.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WaterFallLayout.h; sourceTree = "<group>"; };
 		A7274C4F228EE5EF000E3A07 /* PhotoAndCameraManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PhotoAndCameraManager.swift; sourceTree = "<group>"; };
 		A7274C52228EE635000E3A07 /* LBXScanNetAnimation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LBXScanNetAnimation.swift; sourceTree = "<group>"; };
 		A7274C53228EE635000E3A07 /* LBXScanView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LBXScanView.swift; sourceTree = "<group>"; };
@@ -918,8 +924,6 @@
 		A7D5F23222BB9BE600F8E9AF /* H5CommonViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = H5CommonViewController.swift; sourceTree = "<group>"; };
 		A7D5F24C22BC720000F8E9AF /* WVJBModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WVJBModel.swift; sourceTree = "<group>"; };
 		A7D5F24F22BC7B3700F8E9AF /* WebViewJavascriptBridgeManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebViewJavascriptBridgeManager.swift; sourceTree = "<group>"; };
-		A7D5F25322BF8E6A00F8E9AF /* WaterFallLayout.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WaterFallLayout.h; sourceTree = "<group>"; };
-		A7D5F25422BF8E6A00F8E9AF /* WaterFallLayout.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WaterFallLayout.m; sourceTree = "<group>"; };
 		A7D5F25622C05BE900F8E9AF /* UserDetailModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserDetailModel.swift; sourceTree = "<group>"; };
 		A7D5F25922C05D1400F8E9AF /* SwiftMoyaServiceCommunityApi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftMoyaServiceCommunityApi.swift; sourceTree = "<group>"; };
 		A7D5F25B22C05E0800F8E9AF /* SwiftMoyaNetWorkServiceCommunity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftMoyaNetWorkServiceCommunity.swift; sourceTree = "<group>"; };
@@ -2141,8 +2145,8 @@
 				A72A73722233966800B21995 /* RootModel */,
 				A71738A922898651000AEA6A /* ShopModel */,
 				A7A98E00227E88E8005306E9 /* ProductModel */,
-				BD1DC6C7228D002200B89C57 /* OrderModel */,
 				A79057032276D5FE0037F823 /* ConfigModel */,
+				BD1DC6C7228D002200B89C57 /* OrderModel */,
 				A7284402224DBE3500F82F30 /* UserModel */,
 				A7B4E733228190630012914A /* CMSModel */,
 			);
@@ -3516,8 +3520,8 @@
 		A7D5F25222BF8E6A00F8E9AF /* WaterFallLayout */ = {
 			isa = PBXGroup;
 			children = (
-				A7D5F25322BF8E6A00F8E9AF /* WaterFallLayout.h */,
-				A7D5F25422BF8E6A00F8E9AF /* WaterFallLayout.m */,
+				A72623ED22C4CFD800AEF875 /* WaterFallLayout.h */,
+				A72623EC22C4CFD700AEF875 /* WaterFallLayout.m */,
 			);
 			path = WaterFallLayout;
 			sourceTree = "<group>";
@@ -3536,6 +3540,8 @@
 			children = (
 				A7D5F25E22C0614400F8E9AF /* CommunityTopicCategoryModel.swift */,
 				A72623D222C1FFD100AEF875 /* CommunityPostMyModel.swift */,
+				A72623EA22C4B91900AEF875 /* CommunityPostsModel.swift */,
+				A72623E822C4AFF200AEF875 /* CommunityTopicsModel.swift */,
 			);
 			path = CommunityModel;
 			sourceTree = "<group>";
@@ -4831,7 +4837,6 @@
 				BDF47D7E22827C3F00941AB9 /* ProductSlidingTopBottomCollectionViewCell.swift in Sources */,
 				BD108C9522A60C2100837DAB /* HGImageCollectionViewCell.swift in Sources */,
 				A7FF1589228C854900A85748 /* OrderDetailBottomView.swift in Sources */,
-				A7D5F25522BF8E6B00F8E9AF /* WaterFallLayout.m in Sources */,
 				BD1FC1A722B1075F00D55081 /* UIColor+Expanded.m in Sources */,
 				A7D5F22B22BB687100F8E9AF /* BaseJSWebViewController.swift in Sources */,
 				BD1DC6C5228CFD0B00B89C57 /* SwiftMoyaNetWorkServiceOrder.swift in Sources */,
@@ -4839,6 +4844,7 @@
 				A72A72C422321DE000B21995 /* Extension+CAGradientLayer.swift in Sources */,
 				A7778CA72243A05400C7C47A /* IQKeyboardManagerSwiftManager.swift in Sources */,
 				A7D5F25C22C05E0800F8E9AF /* SwiftMoyaNetWorkServiceCommunity.swift in Sources */,
+				A72623E922C4AFF200AEF875 /* CommunityTopicsModel.swift in Sources */,
 				BD7AB841228438C80030646A /* OrderPaySelfPickAddressCell.swift in Sources */,
 				A7C0FDF022B6538200BC1E86 /* CommunityBannerFSPagerViewCell.swift in Sources */,
 				BD01B20022BC677900CE9F36 /* PublishVideoRecorderController.swift in Sources */,
@@ -4901,6 +4907,7 @@
 				A77F2CCA223209F2001BD3F6 /* BaseTabbarViewController.swift in Sources */,
 				A7BF202B22B396F300396DB3 /* CardContentTitleTableViewCell.swift in Sources */,
 				A70B2C1D2286B52400B2449F /* ProductDetailViewController.swift in Sources */,
+				A72623EE22C4CFD800AEF875 /* WaterFallLayout.m in Sources */,
 				A7D5F25A22C05D1400F8E9AF /* SwiftMoyaServiceCommunityApi.swift in Sources */,
 				A7CC75332271ABB0003C4F38 /* AddressManagerViewController.swift in Sources */,
 				A7FF158C228C911C00A85748 /* OrderRefunddetailsViewController.swift in Sources */,
@@ -5185,6 +5192,7 @@
 				BD1DC6C9228D005000B89C57 /* OrderCreateParameterModel.swift in Sources */,
 				A7BF203422B47E8600396DB3 /* CardContentActionTableViewCell.swift in Sources */,
 				A71AA52622732068008FF1A5 /* SwiftMoyaServiceConfigApi.swift in Sources */,
+				A72623EB22C4B91900AEF875 /* CommunityPostsModel.swift in Sources */,
 				A77F2C982231FD25001BD3F6 /* BaseNavigationViewController.swift in Sources */,
 				A7274C5D228EE636000E3A07 /* LBXScanViewStyle.swift in Sources */,
 				A73911B3229ECE340033177E /* UICollectionViewLeftAlignedLayout.m in Sources */,

+ 1 - 0
RainbowPlanet/RainbowPlanet/Modules/CommunityModule/CommunityFeaturedTopics/ViewController/CommunityFeaturedTopicsViewController.swift

@@ -11,6 +11,7 @@ import UIKit
 class CommunityFeaturedTopicsViewController: BaseViewController {
     
     var cellHeightsDictionary = Dictionary<IndexPath, Any>()
+    var id : Int = 0
     
     override func viewDidLoad() {
         super.viewDidLoad()

+ 49 - 37
RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchContentList/View/SearchContentListCollectionCell.swift

@@ -26,11 +26,6 @@ class SearchContentListCollectionCell: UICollectionViewCell {
     //MARK: - indexPath
     var indexPath: IndexPath?{
         didSet {
-            if self.indexPath?.row == 1 || self.indexPath?.row == 2 {
-                titleLabel.text = "The UCI announced on Thursday that its Anti-Doping Tribunal found Cobo \"guilty of an anti-doping rule violation (Use of a prohibited substance) based on abnormalities from 2009 and 2011 detected in his Biological Passport and imposed a three-year period of ineligibility on the rider.\""
-            } else {
-                titleLabel.text = "Criterium du Dauphine: Van Aert wins stage 4"
-            }
 
         }
     }
@@ -48,10 +43,12 @@ class SearchContentListCollectionCell: UICollectionViewCell {
     
     //MRAK: - 设置View
     private func setupViews() {
+        self.cornerRadius = 4
+        self.masksToBounds = true
         addSubview(contentImageView)
         addSubview(titleLabel)
-        addSubview(iconImageView)
-        addSubview(nameLabel)
+        addSubview(avatarButton)
+        addSubview(nameButton)
         addSubview(likeBtn)
     }
     
@@ -65,41 +62,36 @@ class SearchContentListCollectionCell: UICollectionViewCell {
             make.left.equalTo(contentImageView.snp_left).offset(10)
             make.right.equalTo(contentImageView.snp_right).offset(-10)
         }
-        iconImageView.snp.makeConstraints { (make) in
+        avatarButton.snp.makeConstraints { (make) in
             make.top.equalTo(titleLabel.snp_bottom).offset(10)
             make.left.equalToSuperview().offset(10)
-            make.bottom.equalToSuperview().offset(-15)
             make.size.equalTo(18)
+            make.bottom.equalToSuperview().offset(-15)
+        }
+        nameButton.snp.makeConstraints { (make) in
+            make.centerY.equalTo(avatarButton)
+            make.left.equalTo(avatarButton.snp_right).offset(5)
+            make.right.lessThanOrEqualTo(likeBtn.snp_left).offset(-5)
+            make.height.equalTo(18)
         }
-        
         likeBtn.snp.makeConstraints { (make) in
-            make.top.equalTo(titleLabel.snp_bottom).offset(12)
+            make.centerY.equalTo(avatarButton)
             make.right.equalTo(-13)
-            make.height.equalTo(15)
+            make.height.equalTo(18)
         }
         likeBtn.layoutButton(edgeInsetsStyle: ButtonEdgeInsetsStyle.left, imageTitleSpace: 5)
-        
-        nameLabel.snp.makeConstraints { (make) in
-            make.centerY.equalTo(iconImageView.snp_centerY)
-            make.left.equalTo(iconImageView.snp_right).offset(5)
-            make.right.equalTo(likeBtn.snp_left).offset(-10)
-            make.height.equalTo(16)
-        }
     }
     
     private lazy var contentImageView: UIImageView = {
         let contentImageView = UIImageView()
         contentImageView.image = kImage(name: "pic_preload")
+        contentImageView.contentMode = .scaleAspectFill
+        contentImageView.clipsToBounds = true
         return contentImageView
     }()
     
     private lazy var titleLabel: UILabel = {
         let titleLabel = UILabel()
-//        if self.indexPath?.row == 1 {
-//            titleLabel.text = "The UCI announced on Thursday that its Anti-Doping Tribunal found Cobo \"guilty of an anti-doping rule violation (Use of a prohibited substance) based on abnormalities from 2009 and 2011 detected in his Biological Passport and imposed a three-year period of ineligibility on the rider.\""
-//        } else {
-//            titleLabel.text = "Criterium du Dauphine: Van Aert wins stage 4"
-//        }
         titleLabel.textColor = k262626Color
         titleLabel.font = kMediumFont13
         titleLabel.textAlignment = .left
@@ -107,27 +99,30 @@ class SearchContentListCollectionCell: UICollectionViewCell {
         return titleLabel
     }()
     
-    private lazy var iconImageView: UIImageView = {
-        let iconImageView = UIImageView()
-        iconImageView.image = kImage(name: "pic_preload")
-        return iconImageView
+    private lazy var avatarButton: UIButton = {
+        let avatarButton = UIButton(type: UIButton.ButtonType.custom)
+        avatarButton.setImage(kImage(name: "defaul_tavatar"), for: UIControl.State.normal)
+        avatarButton.cornerRadius = 18/2
+        avatarButton.masksToBounds = true
+        return avatarButton
     }()
     
-    private lazy var nameLabel: UILabel = {
-        let nameLabel = UILabel()
-        nameLabel.text = "Steven Kruijswijk"
-        nameLabel.textColor = k262626Color
-        nameLabel.font = kRegularFont12
-        nameLabel.textAlignment = .left
-        return nameLabel
+    
+    private lazy var nameButton: UIButton = {
+        let nameButton = UIButton(type: UIButton.ButtonType.custom)
+        nameButton.setTitle("昵称", for: UIControl.State.normal)
+        nameButton.setTitleColor(k262626Color, for: UIControl.State.normal)
+        nameButton.titleLabel?.font = kRegularFont12
+        nameButton.contentHorizontalAlignment = .left
+        return nameButton
     }()
     
     private lazy var likeBtn: UIButton = {
         let likeBtn = UIButton(type: UIButton.ButtonType.custom)
         likeBtn.setTitle("8844", for: UIControl.State.normal)
         likeBtn.setTitleColor(k999999Color, for: UIControl.State.normal)
-        likeBtn.setImage(kImage(name: "common_uncheck_icon"), for: UIControl.State.normal)
-        likeBtn.setImage(kImage(name: "common_check_icon"), for: UIControl.State.selected)
+        likeBtn.setImage(kImage(name: "btn_praise"), for: UIControl.State.normal)
+        likeBtn.setImage(kImage(name: "btn_praise_pre_36px"), for: UIControl.State.selected)
         likeBtn.titleLabel?.font = kRegularFont12
         likeBtn.rx.tap.subscribe(onNext: { [weak self] (data) in
             likeBtn.isSelected = !likeBtn.isSelected
@@ -139,4 +134,21 @@ class SearchContentListCollectionCell: UICollectionViewCell {
         return likeBtn
     }()
     
+    var communityPostDataModel : CommunityPostDataModel? {
+        didSet {
+            contentImageView.kf.setImage(with: kURLImage(name: communityPostDataModel?.img ?? ""), placeholder: kImage(name: "pic_preload"))
+            titleLabel.text = communityPostDataModel?.title
+            avatarButton.kf.setImage(with: kURLImage(name: communityPostDataModel?.avatar ?? ""), for: UIControl.State.normal, placeholder: kImage(name: "defaul_tavatar"))
+            nameButton.setTitle(communityPostDataModel?.username, for: UIControl.State.normal)
+            likeBtn.setTitle("\(communityPostDataModel?.praiseCount ?? 0)", for: UIControl.State.normal)
+            if communityPostDataModel?.isLike == 0 {
+                likeBtn.isSelected = false
+            }else {
+                likeBtn.isSelected = true
+            }
+            likeBtn.layoutButton(edgeInsetsStyle: ButtonEdgeInsetsStyle.left, imageTitleSpace: 5)
+        }
+    }
+    
+    
 }

+ 78 - 13
RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchContentList/ViewController/SearchContentListViewController.swift

@@ -11,12 +11,13 @@ import JXSegmentedView
 class SearchContentListViewController: UIViewController {
 
     var keyWord : String = ""
+    var communityPostDataModels = Array<CommunityPostDataModel>()
     
     override func viewDidLoad() {
         super.viewDidLoad()
         setupViews()
         setupLayouts()
-
+        setupData()
         // Do any additional setup after loading the view.
     }
     
@@ -33,11 +34,22 @@ class SearchContentListViewController: UIViewController {
         collectionView.snp.makeConstraints { (make) in
             make.top.equalTo(5)
             make.left.equalTo(0)
-            make.right.equalTo(5)
+            make.right.equalTo(0)
             make.bottom.equalTo(0)
         }
     }
     
+    func setupData() {
+        collectionView.addHeaderWithHeader(withBeginRefresh: true, animation: false) {
+            [weak self] (page) in
+            self?.communityPostsApi(page: page)
+        }
+        collectionView.addFooterWithWithHeader(withAutomaticallyRefresh: true) {
+            [weak self] (page) in
+            self?.communityPostsApi(page: page)
+        }
+    }
+    
     private lazy var collectionView: UICollectionView = {
         let collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: collectionViewLayout)
         collectionView.backgroundColor = kf7f8faColor
@@ -48,35 +60,88 @@ class SearchContentListViewController: UIViewController {
         return collectionView
     }()
     
-    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
-        let collectionViewLayout = UICollectionViewFlowLayout.init()
-        collectionViewLayout.minimumLineSpacing = 5
-        collectionViewLayout.minimumInteritemSpacing =  5
-        collectionViewLayout.scrollDirection = UICollectionView.ScrollDirection.vertical
-        collectionViewLayout.itemSize = CGSize(width: (kScreenWidth - 10)/2, height: 250)
-        collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: kSafeTabBarHeight, right: 5)
-
+//    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
+//        let collectionViewLayout = UICollectionViewFlowLayout.init()
+//        collectionViewLayout.minimumLineSpacing = 5
+//        collectionViewLayout.minimumInteritemSpacing =  5
+//        collectionViewLayout.scrollDirection = UICollectionView.ScrollDirection.vertical
+//        collectionViewLayout.itemSize = CGSize(width: (kScreenWidth - 15)/2, height: 250)
+//        collectionViewLayout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: kSafeTabBarHeight, right: 5)
+//
+//        return collectionViewLayout
+//    }()
+    
+    private lazy var collectionViewLayout: WaterFallLayout = {
+        let collectionViewLayout = WaterFallLayout()
+        collectionViewLayout.delegate = self
         return collectionViewLayout
     }()
     
 }
 
+extension SearchContentListViewController {
+    func communityPostsApi(page:Int) {
+        SwiftMoyaNetWorkServiceCommunity.shared().communityPostsApi(keyword: keyWord, page: page) {
+            [weak self] (communityPostsModel) -> (Void) in
+            let communityPostsModel = communityPostsModel as? CommunityPostsModel
+            if communityPostsModel?.pagination?.currentPage ?? 1  <= communityPostsModel?.pagination?.totalPages ?? 1 {
+                if communityPostsModel?.pagination?.currentPage == 1{
+                    self?.communityPostDataModels.removeAll()
+                }
+                self?.communityPostDataModels = (self?.communityPostDataModels)! + (communityPostsModel?.data!)!
+                self?.collectionView.reloadData()
+                if  self?.communityPostDataModels.count ?? 0 >= communityPostsModel?.pagination?.total ?? 0 {
+                    self?.collectionView.isHiddenFooter(true)
+                }
+            }else {
+                self?.collectionView.endFooterNoMoreData()
+            }
+        }
+    }
+}
+
+
+extension SearchContentListViewController : WaterFallLayoutDelegate {
+    func collectionView(_ collectionView: UICollectionView!, heightOfItemAt indexPath: IndexPath!) -> CGFloat {
+        return 250
+    }
+    func contentInsets(for collectionView: UICollectionView!) -> UIEdgeInsets {
+        return UIEdgeInsets(top: 0, left: 5, bottom: kSafeTabBarHeight, right: 5)
+    }
+    func columenCounts(for collectionView: UICollectionView!) -> Int32 {
+        return 2
+    }
+    func horizontalGap(for collectionView: UICollectionView!) -> CGFloat {
+        return 5
+    }
+    func verticalGap(for collectionView: UICollectionView!) -> CGFloat {
+        return 5
+    }
+}
+
 extension SearchContentListViewController: UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
+    
     func numberOfSections(in collectionView: UICollectionView) -> Int {
-        return 1
+        return communityPostDataModels.isEmpty ? 0 : 1
+//        return 1
+
     }
     
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
-        return 10
+        return communityPostDataModels.isEmpty ? 0 : communityPostDataModels.count
+//        return 10
+
     }
     
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         let cell = SearchContentListCollectionCell.cellWith(collectionView: collectionView, indexPath: indexPath)
+        cell.communityPostDataModel = communityPostDataModels[indexPath.row]
         return cell
     }
     
     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
-        
+        let communityPostDataModel = communityPostDataModels[indexPath.row]
+        NotificationCenter.default.post(name: NSNotification.Name("SearchContentList"), object: communityPostDataModel)
     }
     
 }

+ 15 - 0
RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchResult/ViewController/SearchResultViewController.swift

@@ -86,6 +86,21 @@ class SearchResultViewController: BaseViewController {
                 self?.navigationController?.pushViewController(vc, animated: true)
             }
         }
+        
+        // 话题详情页面
+        observe = NotificationCenter.default.addObserver(forName: NSNotification.Name("CommunityFeaturedTopics"), object: nil, queue: OperationQueue.main) {
+            [weak self] (notification) in
+            let communityTopicDataModel = notification.object as! CommunityTopicDataModel
+            let vc = CommunityFeaturedTopicsViewController()
+            vc.id = communityTopicDataModel.id!
+            self?.navigationController?.pushViewController(vc, animated: true)
+        }
+        
+        // 内容详情页面
+        observe = NotificationCenter.default.addObserver(forName: NSNotification.Name("SearchContentList"), object: nil, queue: OperationQueue.main) {
+            [weak self] (notification) in
+            let communityPostDataModel = notification.object as! CommunityPostDataModel
+        }
     }
     
     private lazy var navigationBarView: SearchResultNavigationbarView = {

+ 7 - 1
RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchTopicList/View/SearchTopicListTableViewCell.swift

@@ -113,6 +113,12 @@ class SearchTopicListTableViewCell: UITableViewCell {
         return lineLabel
     }()
     
+    var communityTopicDataModel: CommunityTopicDataModel? {
+        didSet {
+            iconButton.kf.setImage(with: kURLImage(name: communityTopicDataModel?.img ?? ""), for: UIControl.State.normal, placeholder: kImage(name: "pic_preload"))
+            titleLabel.text = communityTopicDataModel?.name
+            subtitleLabel.text = "\(communityTopicDataModel?.followCount ?? 0)人参与"
+        }
+    }
     
-
 }

+ 48 - 3
RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchTopicList/ViewController/SearchTopicListViewController.swift

@@ -11,13 +11,15 @@ import JXSegmentedView
 class SearchTopicListViewController: UIViewController {
 
     var keyWord : String = ""
+    var communityTopicModels = Array<CommunityTopicDataModel>()
+
     
     override func viewDidLoad() {
         super.viewDidLoad()
         setupViews()
         setupLayouts()
+        setupData()
     }
-    
 
     func setupViews() {
         view.backgroundColor = kf7f8faColor
@@ -37,6 +39,17 @@ class SearchTopicListViewController: UIViewController {
         }
     }
     
+    func setupData() {
+        tableView.addHeaderWithHeader(withBeginRefresh: true, animation: false) {
+            [weak self] (page) in
+            self?.communityTopicsApi(page: page)
+        }
+        tableView.addFooterWithWithHeader(withAutomaticallyRefresh: true) {
+            [weak self] (page) in
+            self?.communityTopicsApi(page: page)
+        }
+    }
+    
     lazy var tableView: UITableView = {
         let tableView = UITableView(frame: CGRect.zero, style: UITableView.Style.plain)
         tableView.backgroundColor = UIColor.white
@@ -49,20 +62,52 @@ class SearchTopicListViewController: UIViewController {
     
 }
 
+extension SearchTopicListViewController {
+    
+    
+    /// 话题列表
+    ///
+    /// - Parameter page: 分页
+    func communityTopicsApi(page:Int) {
+        SwiftMoyaNetWorkServiceCommunity.shared().communityTopicsApi(name: keyWord, page: page) {
+            [weak self] (communityTopicsModel) -> (Void) in
+            let communityTopicsModel = communityTopicsModel as? CommunityTopicsModel
+            if communityTopicsModel?.pagination?.currentPage ?? 1  <= communityTopicsModel?.pagination?.totalPages ?? 1 {
+                if communityTopicsModel?.pagination?.currentPage == 1{
+                    self?.communityTopicModels.removeAll()
+                }
+                self?.communityTopicModels = (self?.communityTopicModels)! + (communityTopicsModel?.data!)!
+                self?.tableView.reloadData()
+                if  self?.communityTopicModels.count ?? 0 >= communityTopicsModel?.pagination?.total ?? 0 {
+                    self?.tableView.isHiddenFooter(true)
+                }
+            }else {
+                self?.tableView.endFooterNoMoreData()
+            }
+        }
+    }
+}
+
 extension SearchTopicListViewController :UITableViewDataSource,UITableViewDelegate  {
     
     
+    func numberOfSections(in tableView: UITableView) -> Int {
+        return communityTopicModels.isEmpty ? 0 : 1
+    }
+    
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
-        return 10
+        return communityTopicModels.isEmpty ? 0 : communityTopicModels.count
     }
     
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = SearchTopicListTableViewCell.cellWith(tableView: tableView, indexPath: indexPath)
+        cell.communityTopicDataModel = communityTopicModels[indexPath.row]
         return cell
     }
     
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
-        
+        let communityTopicDataModel = communityTopicModels[indexPath.row]
+        NotificationCenter.default.post(name: NSNotification.Name("CommunityFeaturedTopics"), object: communityTopicDataModel)
     }
     
 }

+ 1 - 1
RainbowPlanet/RainbowPlanet/Modules/SearchModule/SearchUser/ViewController/SearchUserListViewController.swift

@@ -110,7 +110,7 @@ extension SearchUserListViewController :UITableViewDataSource,UITableViewDelegat
     }
     
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
-        return searchMemberModels.isEmpty ? 0 : 1
+        return searchMemberModels.isEmpty ? 0 : searchMemberModels.count
     }
     
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

+ 63 - 0
RainbowPlanet/RainbowPlanet/Service/Model/CommunityModel/CommunityPostsModel.swift

@@ -0,0 +1,63 @@
+//
+//	CommunityPostsModel.swift
+//	Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
+
+import Foundation 
+import ObjectMapper
+
+
+class CommunityPostsModel : NSObject, Mappable{
+
+	var data : [CommunityPostDataModel]?
+	var pagination : PaginationModel?
+
+
+	class func newInstance(map: Map) -> Mappable?{
+		return CommunityPostsModel()
+	}
+	required init?(map: Map){}
+	private override init(){}
+
+	func mapping(map: Map)
+	{
+		data <- map["data"]
+		pagination <- map["pagination"]
+		
+	}
+
+}
+
+class CommunityPostDataModel : NSObject, Mappable{
+    
+    var avatar : String?
+    var id : Int?
+    var img : String?
+    var isLike : Int?
+    var praiseCount : Int?
+    var title : String?
+    var type : String?
+    var uid : Int?
+    var username : String?
+    
+    
+    class func newInstance(map: Map) -> Mappable?{
+        return CommunityPostDataModel()
+    }
+    required init?(map: Map){}
+    private override init(){}
+    
+    func mapping(map: Map)
+    {
+        avatar <- map["avatar"]
+        id <- map["id"]
+        img <- map["img"]
+        isLike <- map["is_like"]
+        praiseCount <- map["praise_count"]
+        title <- map["title"]
+        type <- map["type"]
+        uid <- map["uid"]
+        username <- map["username"]
+        
+    }
+    
+}

+ 53 - 0
RainbowPlanet/RainbowPlanet/Service/Model/CommunityModel/CommunityTopicsModel.swift

@@ -0,0 +1,53 @@
+//
+//	CommunityTopicsModel.swift
+//	Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
+
+import Foundation 
+import ObjectMapper
+
+
+class CommunityTopicsModel : NSObject, Mappable{
+
+	var data : [CommunityTopicDataModel]?
+	var pagination : PaginationModel?
+
+
+	class func newInstance(map: Map) -> Mappable?{
+		return CommunityTopicsModel()
+	}
+	required init?(map: Map){}
+	private override init(){}
+
+	func mapping(map: Map)
+	{
+		data <- map["data"]
+		pagination <- map["pagination"]
+		
+	}
+}
+
+class CommunityTopicDataModel : NSObject, Mappable{
+    
+    var followCount : Int?
+    var id : Int?
+    var img : String?
+    var name : String?
+    
+    
+    class func newInstance(map: Map) -> Mappable?{
+        return CommunityTopicDataModel()
+    }
+    required init?(map: Map){}
+    private override init(){}
+    
+    func mapping(map: Map)
+    {
+        followCount <- map["follow_count"]
+        id <- map["id"]
+        img <- map["img"]
+        name <- map["name"]
+        
+    }
+    
+}
+

+ 42 - 3
RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceApi/SwiftMoyaServiceCommunity/SwiftMoyaNetWorkServiceCommunity.swift

@@ -70,23 +70,62 @@ public class SwiftMoyaNetWorkServiceCommunity: NSObject {
     }
     
     
-    /// MARK: - 个人中心内容
+    // MARK: - 个人中心内容
     ///
     /// - Parameters:
     ///   - type: 个人中心内容类别
     ///   - completion: 回调
-    func communityPostMyApi(type:CommunityPostMyType,uid:Int,page:Int,completion: @escaping apiCallBack) {
+    func communityPostMyApi(type:CommunityPostMyType,uid:Int,page:Int = 1,completion: @escaping apiCallBack) {
         var parameters = Dictionary<String,Any>()
         parameters.updateValue(type.rawValue, forKey: "type")
 //        parameters.updateValue(uid, forKey: "uid")
         parameters.updateValue(90, forKey: "uid")
         parameters.updateValue(page, forKey: "page")
-        parameters.updateValue(5, forKey: "per_page")
         SwiftProgressHUD.shared().showWait()
         SwiftMoyaNetWorkManager.shared.requestObject(CommunityPostMyModel.self, target: MultiTarget(SwiftMoyaServiceCommunityApi.communityPostMy(parameters: parameters))) { (communityPostMyModel) in
             SwiftProgressHUD.shared().hide()
             completion(communityPostMyModel)
         }
     }
+    
+    // MARK: - 话题列表
+    /// 话题列表
+    ///
+    /// - Parameters:
+    ///   - name: 关键字
+    ///   - page: 分页
+    ///   - completion: 回调
+    func communityTopicsApi(categoryId:Int = 0, isSuggest:Int = 0,name:String = "",page:Int = 1,completion: @escaping apiCallBack) {
+        var parameters = Dictionary<String,Any>()
+        parameters.updateValue(isSuggest, forKey: "is_suggest")
+        parameters.updateValue(categoryId, forKey: "category_id")
+        parameters.updateValue(name, forKey: "name")
+        parameters.updateValue(page, forKey: "page")
+        SwiftProgressHUD.shared().showWait()
+        SwiftMoyaNetWorkManager.shared.requestObject(CommunityTopicsModel.self, target: MultiTarget(SwiftMoyaServiceCommunityApi.communityTopics(parameters: parameters))) { (communityTopicsModel) in
+            SwiftProgressHUD.shared().hide()
+            completion(communityTopicsModel)
+        }
+    }
+    
+    // MARK: - 话题列表
+    /// 内容列表
+    ///
+    /// - Parameters:
+    ///   - keyword: 关键字搜索:标题,内容
+    ///   - topicIds: 话题ids,json字符串,[1,2],推荐内容用
+    ///   - page: 分页
+    ///   - completion: 回调
+    func communityPostsApi(keyword:String = "",topicIds : String = "",page:Int = 1,completion: @escaping apiCallBack) {
+        var parameters = Dictionary<String,Any>()
+        parameters.updateValue(keyword, forKey: "keyword")
+        parameters.updateValue(topicIds, forKey: "topic_ids")
+        parameters.updateValue(page, forKey: "page")
+        SwiftProgressHUD.shared().showWait()
+        SwiftMoyaNetWorkManager.shared.requestObject(CommunityPostsModel.self, target: MultiTarget(SwiftMoyaServiceCommunityApi.communityPosts(parameters: parameters))) { (communityPostsModel) in
+            SwiftProgressHUD.shared().hide()
+            completion(communityPostsModel)
+        }
+    }
         
 }

+ 34 - 4
RainbowPlanet/RainbowPlanet/Service/SwiftMoyaService/SwiftMoyaServiceApi/SwiftMoyaServiceCommunity/SwiftMoyaServiceCommunityApi.swift

@@ -21,10 +21,28 @@ public let kCommunityMemberFollowTopicApi = "/community/memberFollowTopic"
 /// 个人中心内容
 public let kCommunityPostMyApi = "/community/post/my"
 
+// MARK: - 话题列表
+/// 话题列表
+public let kCommunityTopicsApi = "/community/topic"
+
+// MARK: - 内容列表
+/// 内容列表
+public let kCommunityPostsApi = "/community/post"
+
+
+/// 社区
+///
+/// - communityTopicCategory: 话题组列表
+/// - communityMemberFollowTopic: 关注推荐话题
+/// - communityPostMy: 个人中心内容
+/// - communityTopics: 话题列表
+/// - communityPosts: 内容列表
 public enum SwiftMoyaServiceCommunityApi {
     case communityTopicCategory(parameters:Dictionary<String, Any>)
     case communityMemberFollowTopic(parameters:Dictionary<String, Any>)
     case communityPostMy(parameters:Dictionary<String, Any>)
+    case communityTopics(parameters:Dictionary<String, Any>)
+    case communityPosts(parameters:Dictionary<String, Any>)
 }
 
 extension SwiftMoyaServiceCommunityApi: TargetType {
@@ -33,7 +51,9 @@ extension SwiftMoyaServiceCommunityApi: TargetType {
         switch self {
         case .communityTopicCategory,
              .communityMemberFollowTopic,
-             .communityPostMy
+             .communityPostMy,
+             .communityTopics,
+             .communityPosts
             :
             return URL(string: kApiDataPrefix())!
         }
@@ -47,6 +67,10 @@ extension SwiftMoyaServiceCommunityApi: TargetType {
             return kCommunityMemberFollowTopicApi
         case .communityPostMy:
             return kCommunityPostMyApi
+        case .communityTopics:
+            return kCommunityTopicsApi
+        case .communityPosts:
+            return kCommunityPostsApi
         }
     }
     
@@ -56,7 +80,9 @@ extension SwiftMoyaServiceCommunityApi: TargetType {
             :
             return .post
         case .communityTopicCategory,
-             .communityPostMy
+             .communityPostMy,
+             .communityTopics,
+             .communityPosts
             :
             return .get
             
@@ -68,7 +94,9 @@ extension SwiftMoyaServiceCommunityApi: TargetType {
         switch self {
         case .communityTopicCategory(var parameters),
              .communityMemberFollowTopic(var parameters),
-             .communityPostMy(var parameters)
+             .communityPostMy(var parameters),
+             .communityTopics(var parameters),
+             .communityPosts(var parameters)
             :
             let sign = SwiftSign.shared().sign(signType:.AccessToken, parameters: parameters)
             parameters.updateValue(sign, forKey: "sign")
@@ -93,7 +121,9 @@ extension SwiftMoyaServiceCommunityApi: TargetType {
         switch self {
         case .communityTopicCategory,
              .communityMemberFollowTopic,
-             .communityPostMy
+             .communityPostMy,
+             .communityTopics,
+             .communityPosts
             :
             return (headerParameters(headerType: .tokenHeader) as! [String : String])
         }

+ 23 - 29
RainbowPlanet/RainbowPlanet/Tools/WaterFallLayout/WaterFallLayout.h

@@ -1,49 +1,43 @@
 //
 //  WaterFallLayout.h
-//  WateFallLayoutTest
+//  layout
 //
-//  Created by 刘梦桦 on 2017/5/18.
-//  Copyright © 2017年 . All rights reserved.
+//  Created by meterscao on 16/5/23.
+//  Copyright © 2016年 meters. All rights reserved.
 //
 
 #import <UIKit/UIKit.h>
 
-@class WaterFallLayout;
-
-@protocol  WaterFallLayoutDeleaget<NSObject>
+@protocol WaterFallLayoutDelegate <NSObject>
 
 @required
-/**
- * 每个item的高度
- */
-- (CGFloat)waterFallLayout:(WaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth;
+// 瀑布流视图每个元素的高度
+// 必须实现的方法
+-(CGFloat)collectionView:(UICollectionView *)collectionView heightOfItemAtIndexPath:(NSIndexPath *)indexPath;
 
 @optional
-/**
- * 有多少列
- */
-- (NSUInteger)columnCountInWaterFallLayout:(WaterFallLayout *)waterFallLayout;
-
-/**
- * 每列之间的间距
- */
-- (CGFloat)columnMarginInWaterFallLayout:(WaterFallLayout *)waterFallLayout;
+// 瀑布流内容区域上下左右的边距
+// 默认为 10,10,10,10
+-(UIEdgeInsets)contentInsetsForCollectionView:(UICollectionView *)collectionView;
 
-/**
- * 每行之间的间距
- */
-- (CGFloat)rowMarginInWaterFallLayout:(WaterFallLayout *)waterFallLayout;
+// 瀑布流视图需要展示的列数
+// 默认为 2 列
+-(int)columenCountsForCollectionView:(UICollectionView *)collectionView;;
 
-/**
- * 每个item的内边距
- */
-- (UIEdgeInsets)edgeInsetdInWaterFallLayout:(WaterFallLayout *)waterFallLayout;
+// 瀑布流视图每列之间横向的间距
+// 默认为 10
+-(CGFloat)horizontalGapForCollectionView:(UICollectionView *)collectionView;
 
+// 瀑布流视图每个元素之间纵向的间距
+// 默认为 10
+-(CGFloat)verticalGapForCollectionView:(UICollectionView *)collectionView;
 
 @end
 
+
+
 @interface WaterFallLayout : UICollectionViewLayout
-/** 代理 */
-@property (nonatomic, weak) id<WaterFallLayoutDeleaget> delegate;
+
+@property (nonatomic) id<WaterFallLayoutDelegate> delegate;
 
 @end

+ 114 - 166
RainbowPlanet/RainbowPlanet/Tools/WaterFallLayout/WaterFallLayout.m

@@ -1,225 +1,173 @@
 //
 //  WaterFallLayout.m
-//  WateFallLayoutTest
+//  layout
 //
-//  Created by 刘梦桦 on 2017/5/18.
-//  Copyright © 2017年 . All rights reserved.
+//  Created by meterscao on 16/5/23.
+//  Copyright © 2016年 meters. All rights reserved.
 //
 
 #import "WaterFallLayout.h"
 
-/** 默认的列数    */
-static const CGFloat DefaultColunmCount = 2;
-/** 每一列之间的间距    */
-static const CGFloat DefaultColunmMargin = 10;
+@interface WaterFallLayout ()
 
-/** 每一行之间的间距    */
-static const CGFloat DefaultRowMargin = 10;
+@property (nonatomic) UIEdgeInsets contentInsets;
 
-/** 内边距    */
-static const UIEdgeInsets DefaultEdgeInsets = {10,10,10,10};
+@property (nonatomic) int columnCounts;
+@property (nonatomic) CGFloat columnWidth;
 
+@property (nonatomic) CGFloat gapHorizontal;
+@property (nonatomic) CGFloat gapVertical;
 
-@interface WaterFallLayout()
-/** 存放所有的布局属性 */
-@property (nonatomic, strong) NSMutableArray * attrsArr;
-/** 存放所有列的当前高度 */
-@property (nonatomic, strong) NSMutableArray *columnHeights;
-/** 内容的高度 */
-@property (nonatomic, assign) CGFloat contentHeight;
+@property (nonatomic) NSMutableArray *YArray;
 
-- (NSUInteger)colunmCount;
-- (CGFloat)columnMargin;
-- (CGFloat)rowMargin;
-- (UIEdgeInsets)edgeInsets;
+@property (nonatomic) CGFloat containerWidth;
 
 @end
 
 @implementation WaterFallLayout
 
+#pragma mark - 基本实现
+- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
+    return YES;
+}
 
 
-#pragma mark 懒加载
-- (NSMutableArray *)attrsArr{
-    if (!_attrsArr) {
-        _attrsArr = [NSMutableArray array];
-    }
+-(void)prepareLayout{
     
-    return _attrsArr;
-}
-
-- (NSMutableArray *)columnHeights{
-    if (!_columnHeights) {
-        _columnHeights = [NSMutableArray array];
+    [super prepareLayout];
+    
+    [self initConfit];
+    
+    
+    // 计算出各个尺寸
+    self.containerWidth = self.collectionView.frame.size.width ;
+    
+    self.YArray =  [[NSMutableArray alloc]initWithCapacity:self.columnCounts];
+    
+    for (int index = 0; index < self.columnCounts; index ++) {
+        self.YArray[index] = @(self.contentInsets.top);
     }
     
-    return _columnHeights;
+    self.columnWidth = ( self.containerWidth - self.contentInsets.left - self.contentInsets.right - self.gapHorizontal * (self.columnCounts - 1)) / self.columnCounts;
+    
 }
 
-#pragma mark - 数据处理
-/**
- * 列数
- */
-- (NSUInteger)colunmCount{
+// 返回当前瀑布流视图整个内容区域的高度
+-(CGSize)collectionViewContentSize{
     
-    if ([self.delegate respondsToSelector:@selector(columnCountInWaterFallLayout:)]) {
-        return [self.delegate columnCountInWaterFallLayout:self];
-    }else{
-        return DefaultColunmCount;
-    }
+    return CGSizeMake(self.containerWidth,
+                      [self.YArray[[self indexOfMaxY]] floatValue] - self.gapVertical + self.contentInsets.bottom);
 }
 
-/**
- * 列间距
- */
-- (CGFloat)columnMargin{
-    if ([self.delegate respondsToSelector:@selector(columnMarginInWaterFallLayout:)]) {
-        return [self.delegate columnMarginInWaterFallLayout:self];
-    }else{
-        return DefaultColunmMargin;
-    }
-}
+-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
 
-/**
- * 行间距
- */
-- (CGFloat)rowMargin{
-    if ([self.delegate respondsToSelector:@selector(rowMarginInWaterFallLayout:)]) {
-        return [self.delegate rowMarginInWaterFallLayout:self];
-    }else{
-        return DefaultRowMargin;
+    NSMutableArray *layoutAttibutes = [[NSMutableArray alloc]init];
+    
+    for (int i = 0 ; i < [self.collectionView numberOfItemsInSection:0]; i ++) {
+        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
+        [layoutAttibutes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
     }
-}
+    
+    return layoutAttibutes;
 
-/**
- * item的内边距
- */
-- (UIEdgeInsets)edgeInsets{
-    if ([self.delegate respondsToSelector:@selector(edgeInsetdInWaterFallLayout:)]) {
-        return [self.delegate edgeInsetdInWaterFallLayout:self];
-    }else{
-        return DefaultEdgeInsets;
-    }
 }
 
-
-
-/**
- * 初始化
- */
-- (void)prepareLayout{
+-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
     
-    [super prepareLayout];
+    CGFloat x,y,itemWidth,itemHeight;
     
-    self.contentHeight = 0;
+    int index = [self indexOfMinY];
     
-    // 清楚之前计算的所有高度
-    [self.columnHeights removeAllObjects];
+    x = [self XOfColumn:index];
+    y = [self.YArray[index] floatValue];
+    itemWidth =  self.columnWidth;
+    itemHeight = [self.delegate collectionView:self.collectionView heightOfItemAtIndexPath:indexPath];
     
-    // 设置每一列默认的高度
-    for (NSInteger i = 0; i < DefaultColunmCount ; i ++) {
-        [self.columnHeights addObject:@(DefaultEdgeInsets.top)];
+    // 更新插入新的item之后,当前列的底部纵坐标
+    self.YArray[index] = @(y + itemHeight + self.gapHorizontal);
+   
+    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
+    attributes.frame = CGRectMake(x, y, itemWidth, itemHeight);
+    return attributes;
+
+}
+
+
+#pragma mark - 初始化
+-(void)initConfit{
+    // 初始化各项配置
+    if ([self.delegate respondsToSelector:@selector(contentInsetsForCollectionView:)]) {
+        self.contentInsets = [self.delegate contentInsetsForCollectionView:self.collectionView];
+    }
+    else{
+        self.contentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
     }
     
     
-    // 清楚之前所有的布局属性
-    [self.attrsArr removeAllObjects];
-    
-    // 开始创建每一个cell对应的布局属性
-    NSInteger count = [self.collectionView numberOfItemsInSection:0];
+    if ([self.delegate respondsToSelector:@selector(horizontalGapForCollectionView:)]) {
+        self.gapHorizontal = [self.delegate horizontalGapForCollectionView:self.collectionView];
+    }
+    else{
+        self.gapHorizontal = 10.f;
+    }
     
-    for (int i = 0; i < count; i++) {
-        
-        // 创建位置
-        NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
-        
-        // 获取indexPath位置上cell对应的布局属性
-        UICollectionViewLayoutAttributes * attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
-        
-        [self.attrsArr addObject:attrs];
+    if ([self.delegate respondsToSelector:@selector(verticalGapForCollectionView:)]) {
+        self.gapVertical = [self.delegate verticalGapForCollectionView:self.collectionView];
+    }
+    else{
+        self.gapVertical = 10.f;
     }
     
+    
+    if ([self.delegate respondsToSelector:@selector(columenCountsForCollectionView:)]) {
+        self.columnCounts = [self.delegate columenCountsForCollectionView:self.collectionView];
+    }
+    else{
+        self.columnCounts = 2;
+    }
+
 }
 
+#pragma mark - 工具函数
 
-/**
- * 返回indexPath位置cell对应的布局属性
- */
-- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
-    
-    // 创建布局属性
-    UICollectionViewLayoutAttributes * attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
-    
-    //collectionView的宽度
-    CGFloat collectionViewW = self.collectionView.frame.size.width;
+// 计算当前列的横坐标
+-(CGFloat)XOfColumn:(int)index{
     
-    // 设置布局属性的frame
+    return self.contentInsets.left + (self.columnWidth + self.gapHorizontal)*index;
     
-    CGFloat cellW = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.colunmCount - 1) * self.columnMargin) / self.colunmCount;
-    CGFloat cellH = [self.delegate waterFallLayout:self heightForItemAtIndexPath:indexPath.item itemWidth:cellW];
+}
+
 
+// 筛选出当前纵坐标最小的列,用以确定新的item插入到哪一列
+-(int)indexOfMinY{
     
-    // 找出最短的那一列
-    NSInteger destColumn = 0;
-    CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
+    int resultIndex = 0;
+    CGFloat minY = [self.YArray[0] floatValue];
     
-    for (int i = 1; i < DefaultColunmCount; i++) {
-        
-        // 取得第i列的高度
-        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
-        
-        if (minColumnHeight > columnHeight) {
-            minColumnHeight = columnHeight;
-            destColumn = i;
+    for (int index = 1; index < self.columnCounts; index ++ ) {
+        if([self.YArray[index] floatValue] < minY ){
+            minY = [self.YArray[index] floatValue];
+            resultIndex = index;
         }
     }
     
-    CGFloat cellX = self.edgeInsets.left + destColumn * (cellW + self.columnMargin);
-    CGFloat cellY = minColumnHeight;
-    if (cellY != self.edgeInsets.top) {
-        
-        cellY += self.rowMargin;
-    }
-    
-    attrs.frame = CGRectMake(cellX, cellY, cellW, cellH);
-    
-    // 更新最短那一列的高度
-    self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
-    
-    // 记录内容的高度 - 即最长那一列的高度
-    CGFloat maxColumnHeight = [self.columnHeights[destColumn] doubleValue];
-    if (self.contentHeight < maxColumnHeight) {
-        self.contentHeight = maxColumnHeight;
-    }
-    
-    return attrs;
+    return resultIndex;
 }
 
-/**
- * 决定cell的高度
- */
-- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
-    
-    return self.attrsArr;
-}
 
-/**
- * 内容的高度
- */
-- (CGSize)collectionViewContentSize{
- 
-//    CGFloat maxColumnHeight = [self.columnHeights[0] doubleValue];
-//    for (int i = 0; i < DefaultColunmCount; i++) {
-//        
-//        // 取得第i列的高度
-//        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
-//        
-//        if (maxColumnHeight < columnHeight) {
-//            maxColumnHeight = columnHeight;
-//        }
-//
-//    }
+// 筛选出当前纵坐标最大的列,用以确定整个视图的高度
+-(int)indexOfMaxY{
+    int resultIndex = 0;
+    CGFloat maxY = [self.YArray[0] floatValue];
     
-    return CGSizeMake(0, self.contentHeight + self.edgeInsets.bottom);
+    for (int index = 1; index < self.columnCounts; index ++ ) {
+        if([self.YArray[index] floatValue] > maxY ){
+            maxY = [self.YArray[index] floatValue];
+            resultIndex = index;
+        }
+    }
+    return resultIndex;
 }
+
+
 @end