最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

[已解决]swift表格视图 gridview

iOS crifan 1115浏览 0评论

swift gridview

UICollectionView Tutorial Part 1: Getting Started

IOS SWIFT—使用UICollectionView – WRH的专栏 – 博客频道 – CSDN.NET

Create 3 column grid view with UICollectionView

al7/ALGridView: Simple Grid View in Swift

ios – Grid layout with CollectionView in Swift – Stack Overflow

Building a Grid Layout with UICollectionView and Realm Swift

swift grid lib github

CosmicMind/Material: Material is an animation and graphics framework that allows developers to easily create beautiful applications.

swift grid view

UICollectionView Tutorial Part 2: Reusable Views and Cell Selection

cemolcay/ReorderableGridView-Swift: reorderable grid view solution implemented with swift. its UIScrollView subclass, its not a collection view layout.

iOS Programming Tutorial: Create Grid Layout Using UICollectionView

swift table grid view

Table with many columns ios swift – Stack Overflow

Scrollable Multicolumn Table for iPad for iOS – Cocoa Controls

linox/Scrollable-MultiColumnTable-for-iPad

asifmujteba/ASFTableView: A customizable Web like multi-column table view for iOS with header and inner rows

MultiColumnTableViewForiOS for iOS – Cocoa Controls

->

Xenofex/MultiColumnTableViewForiOS: Implemented a multi-column table view based on the UITableView for iOS

NGrid Swift Tutorial

->

NChart3D – awesome charting for iOS, Android and OS X. NGrid – iOS grids, tables & spreadsheets

“After you have downloaded the package, you’ll get a 30-day trial license key."

uitableview – How to create grid table view in iphone – Stack Overflow

scasserly/GridTableView: Demonstrates how to create a grid using UITableView

Grid Table View | 代码例子区 – CocoaChina CocoaChina_让移动开发更简单

iOS / iPhone / iPad 实现网格化视图(Grid View),或者可以视作为多列的表格 代码 Grid Table View 视图布局(View Layout)开源代码 – Code4App.com

iOS / iPhone / iPad 快速生成表格,极方便地创建表格视图 代码 KWFormView 图表(Chart)开源代码 – Code4App.com

先去试试:

UICollectionView using horizontal and vertical scrolling with sticky rows and columns | Brightec, Brighton, UK

->

brightec/CustomCollectionViewLayout: Custom layout for a collection view using horizontal and vertical scrolling with sticky rows and columns

尝试用Carthage安装:

github "brightec/CustomCollectionViewLayout"

结果出错:

licrifandeMacBook-Pro:SalesAppiOS crifan$ carthage update CustomCollectionViewLayout –platform iOS
*** Cloning CustomCollectionViewLayout
No tagged versions found for github "brightec/CustomCollectionViewLayout"

直接下载和导入源码吧

最后用代码:

//
//  PotentialAnalysisReportViewController.swift
//  SalesApp
//
//  Created by licrifan on 16/6/29.
//  Copyright © 2016年 licrifan. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class StateColumnItem {
    var titleName:String = ""
    var titleKey:String = ""
    init(titleName:String = "", titleKey:String = ""){
        self.titleName = titleName
        self.titleKey = titleKey
    }
}
let StateColumnItemList:[StateColumnItem] = [
    StateColumnItem(titleName: "H", titleKey: "0"),
    StateColumnItem(titleName: "A", titleKey: "1"),
    StateColumnItem(titleName: "B", titleKey: "2"),
    StateColumnItem(titleName: "C", titleKey: "3"),
    StateColumnItem(titleName: "D", titleKey: "4"),
    StateColumnItem(titleName: "N", titleKey: "5"),
    StateColumnItem(titleName: "下订", titleKey: "6"),
    StateColumnItem(titleName: "交车", titleKey: "9"),
    StateColumnItem(titleName: "退订", titleKey: "10"),
    StateColumnItem(titleName: "退车", titleKey: "11"),
    StateColumnItem(titleName: "战败", titleKey: "12"),
]
enum AnalysisColumnIndex:Int {
    case State  = 0
    case Today  = 1
    case Week   = 2
    case Month  = 3
    case Year   = 4
}
//let PotentialAnalysisRowNumber:Int = 12
let PotentialAnalysisRowNumber:Int = 1 + StateColumnItemList.count
let PotentialAnalysisColumnNumber:Int = 5
let PotentialAnalysisLabelFont:UIFont = UIFont.systemFontOfSize(12)
let PotentialAnalysisLabelHorizontalBackgroundColor:UIColor = HomeVerticalLineColor
let PotentialAnalysisLabelVerticalBackgroundColor:UIColor = UIColor(hexString: "#FAFAFA")!
class PotentialAnalysisReportViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    let dateCellIdentifier = "DateCellIdentifier"
    let contentCellIdentifier = "ContentCellIdentifier"
    var collectionView: UICollectionView
    init(){
        let collectionViewFrame:CGRect = CGRectMake(
            0,
            0,
            ScreenWidth,
            ScreenHeight – (SingletonRootNC().navigationBar.frame.height + UIApplication.sharedApplication().statusBarFrame.height))
        gLog.verbose("collectionViewFrame=\(collectionViewFrame)")
        //collectionViewFrame=(0.0, 0.0, 320.0, 504.0)
        //collection view layout
        let collectionViewLayout:CustomCollectionViewLayout = CustomCollectionViewLayout()
        collectionViewLayout.numberOfColumns = PotentialAnalysisColumnNumber
        gLog.verbose("collectionViewLayout=\(collectionViewLayout)")
        //collectionViewLayout=<Sales_App.CustomCollectionViewLayout: 0x7b1a7ca0>
        self.collectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: collectionViewLayout)
        super.init(nibName: nil, bundle: nil)
        self.checkPotentialAnalysis()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /*************************************************************************
     * View Controller Functions
     *************************************************************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "潜客分析报表"
        self.view.backgroundColor = AppBackgoundColor
        self.collectionView.registerNib(
            UINib(nibName: "DateCollectionViewCell", bundle: nil),
            forCellWithReuseIdentifier: dateCellIdentifier
        )
        self.collectionView.registerNib(
            UINib(nibName: "ContentCollectionViewCell", bundle: nil),
            forCellWithReuseIdentifier: contentCellIdentifier
        )
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(self.collectionView)
    }
    /*************************************************************************
     * UICollectionViewDataSource Functions
     *************************************************************************/
    //row
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return PotentialAnalysisRowNumber
    }
    //column
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return PotentialAnalysisColumnNumber
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        gLog.verbose("collectionView=\(collectionView)")
        gLog.debug("indexPath=\(indexPath)")
        if indexPath.section == 0 {
            let titleCell: DateCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(dateCellIdentifier, forIndexPath: indexPath) as! DateCollectionViewCell
            titleCell.dateLabel.font = PotentialAnalysisLabelFont
            titleCell.dateLabel.textColor = CommonTextColorBlack
            titleCell.backgroundColor = PotentialAnalysisLabelHorizontalBackgroundColor
            var curHorizontalTitle = ""
            switch indexPath.row {
            case AnalysisColumnIndex.State.rawValue:
                curHorizontalTitle = "状态"
            case AnalysisColumnIndex.Today.rawValue:
                curHorizontalTitle = "当日"
            case AnalysisColumnIndex.Week.rawValue:
                curHorizontalTitle = "当周"
            case AnalysisColumnIndex.Month.rawValue:
                curHorizontalTitle = "当月"
            case AnalysisColumnIndex.Year.rawValue:
                curHorizontalTitle = "当年"
            default:
                break
            }
            titleCell.dateLabel.text = curHorizontalTitle
            return titleCell
        } else {
            if indexPath.row == 0 {
                let titleCell : DateCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(dateCellIdentifier, forIndexPath: indexPath) as! DateCollectionViewCell
                titleCell.dateLabel.font = PotentialAnalysisLabelFont
                titleCell.dateLabel.textColor = CommonTextColorBlack
                titleCell.backgroundColor = PotentialAnalysisLabelVerticalBackgroundColor
                var curVerticalTitle = ""
                let titleIndex = indexPath.section – 1
                switch indexPath.section {
                case 1…StateColumnItemList.count:
                    curVerticalTitle = StateColumnItemList[titleIndex].titleName
                default:
                    break
                }
                titleCell.dateLabel.text = curVerticalTitle
                return titleCell
            } else {
                let contentCell: ContentCollectionViewCell = collectionView .dequeueReusableCellWithReuseIdentifier(contentCellIdentifier, forIndexPath: indexPath) as! ContentCollectionViewCell
                contentCell.contentLabel.font = PotentialAnalysisLabelFont
                contentCell.contentLabel.textColor = CommonContentTextColorBlack
                var curAnalysisValue = 0
                gLog.verbose("indexPath=\(indexPath)")
                let valueRowIdx = indexPath.section – 1
                gLog.verbose("valueRowIdx=\(valueRowIdx)")
                var curDictKey = ""
                switch indexPath.row {
                case AnalysisColumnIndex.Today.rawValue:
                    curDictKey = "today"
                case AnalysisColumnIndex.Week.rawValue:
                    curDictKey = "week"
                case AnalysisColumnIndex.Month.rawValue:
                    curDictKey = "month"
                case AnalysisColumnIndex.Year.rawValue:
                    curDictKey = "year"
                default:
                    break
                }
                if curDictKey.notEmpty {
                    if let valueList = gCurUserItem.potentialAnalysisDict[curDictKey] {
                        curAnalysisValue = valueList[valueRowIdx]
                    }
                }
                gLog.verbose("curAnalysisValue=\(curAnalysisValue)")
                contentCell.contentLabel.text = String(curAnalysisValue)
                return contentCell
            }
        }
    }
    func checkPotentialAnalysis(){
        gLog.verbose("gCurUserItem.potentialAnalysisDict=\(gCurUserItem.potentialAnalysisDict)")
        if gCurUserItem.potentialAnalysisDict.keys.isEmpty {
            getUrlRespDataJson_async(
                .GET,
                url: ServerApi.getPotentialAnalysisUrl(gCurUserItem.id),
                respJsonHandler: self.getPotentialAnalysisHandler)
//        } else {
//            initPotientialAnalysisDict()
        }
    }
//    func initPotientialAnalysisDict(){
//        var analysisValueList:[Int] = [Int]()
//        
////        var analysisKeyList = [String]()
//        for _ in StateColumnItemList {
////            analysisKeyList.append(eachStateItem.titleKey)
//            analysisValueList.append(0)
//        }
//        
//        gCurUserItem.potentialAnalysisDict["today"] = analysisValueList
//        gCurUserItem.potentialAnalysisDict["week"] = analysisValueList
//        gCurUserItem.potentialAnalysisDict["month"] = analysisValueList
//        gCurUserItem.potentialAnalysisDict["year"] = analysisValueList
//        
//        gLog.verbose("gCurUserItem.potentialAnalysisDict=\(gCurUserItem.potentialAnalysisDict)")
//    }
    func getPotentialAnalysisHandler(respDataJson:Alamofire.Result<JSON, NSError>, mergedAllPara:Dictionary<String, AnyObject>) {
        gLog.verbose("respDataJson.debugDescription=\(respDataJson.debugDescription)")
        /*
        {
          "today" : {
            "3" : 0,
            "11" : 0,
            "4" : 0,
            "0" : 0,
            "9" : 0,
            "5" : 0,
            "1" : 0,
            "12" : 0,
            "6" : 0,
            "2" : 0,
            "10" : 0
          },
          "year" : {
            "3" : 13,
            "11" : 21,
            "4" : 7,
            "0" : 10,
            "9" : 1,
            "5" : 2,
            "1" : 8,
            "12" : 0,
            "6" : 1,
            "2" : 6,
            "10" : 2
          },
          "week" : {
            "3" : 1,
            "11" : 0,
            "4" : 0,
            "0" : 0,
            "9" : 0,
            "5" : 0,
            "1" : 0,
            "12" : 0,
            "6" : 0,
            "2" : 1,
            "10" : 0
          },
          "month" : {
            "3" : 13,
            "11" : 21,
            "4" : 7,
            "0" : 10,
            "9" : 1,
            "5" : 2,
            "1" : 8,
            "12" : 0,
            "6" : 1,
            "2" : 6,
            "10" : 2
          }
        }
         */
        switch respDataJson {
        case .Success(let dataJson):
            gLog.verbose("dataJson=\(dataJson)")
            guard let analysisDict = dataJson.dictionary else {
                gLog.error("get empty potential customer analysis dict")
                return
            }
//            var curAnalysisDict = [String:[String:Int]]()
            var curAnalysisDict = [String:[Int]]()
            for eachAnalysisKey in analysisDict.keys {
                gLog.verbose("eachAnalysisKey=\(eachAnalysisKey)")
                let eachAnalysisJson = analysisDict[eachAnalysisKey]!
                gLog.verbose("eachAnalysisJson=\(eachAnalysisJson)")
                let curAnalysisItem = parseJsonToAnalysisItem(eachAnalysisJson)
                gLog.verbose("curAnalysisItem=\(curAnalysisItem)")
                curAnalysisDict[eachAnalysisKey] = curAnalysisItem
            }
            gCurUserItem.potentialAnalysisDict = curAnalysisDict
            gLog.verbose("gCurUserItem.potentialAnalysisDict=\(gCurUserItem.potentialAnalysisDict)")
            //gCurUserItem.potentialAnalysisDict=["today": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "year": [10, 8, 6, 13, 7, 2, 1, 1, 2, 21, 0], "week": [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], "month": [10, 8, 6, 13, 7, 2, 1, 1, 2, 21, 0]]
            dispatchMain_async({
                self.collectionView.reloadData()
            })
        case .Failure(let error):
            gLog.verbose("error=\(error)")
        }
    }
}

注:

其中对于原有的:

CustomCollectionViewLayout.swift

中有少许改动:

class CustomCollectionViewLayout: UICollectionViewLayout {
//    let numberOfColumns = 8
    var numberOfColumns = 8

然后后来为了允许自定义(CGSize类型的)itemSize:

        let collectionViewLayout:CustomCollectionViewLayout = CustomCollectionViewLayout()
        collectionViewLayout.numberOfColumns = PotentialAnalysisColumnNumber
        let eachItemSize = CGSize(width: ScreenWidth/CGFloat(collectionViewLayout.numberOfColumns), height: 30)
        let itemSizeColumnList = Array<CGSize>(count: collectionViewLayout.numberOfColumns, repeatedValue: eachItemSize)
        gLog.verbose("eachItemSize=\(eachItemSize), itemSizeColumnList=\(itemSizeColumnList)")
        //eachItemSize=(64.0, 30.0), itemSizeColumnList=[(64.0, 30.0), (64.0, 30.0), (64.0, 30.0), (64.0, 30.0), (64.0, 30.0)]
        collectionViewLayout.itemsSize = itemSizeColumnList
        gLog.verbose("collectionViewLayout=\(collectionViewLayout)")
        //collectionViewLayout=<Sales_App.CustomCollectionViewLayout: 0x7b1a7ca0>
        self.collectionView = UICollectionView(frame: collectionViewFrame, collectionViewLayout: collectionViewLayout)

然后把整个CustomCollectionViewLayout改动了不少,主要是语法上面的和个别变量全局化的:

//
//  CustomCollectionViewLayout.swift
//  CustomCollectionLayout
//
//  Created by JOSE MARTINEZ on 15/12/2014.
//  Copyright (c) 2014 brightec. All rights reserved.
//
import UIKit
class CustomCollectionViewLayout: UICollectionViewLayout {
//    let numberOfColumns = 8
    var numberOfColumns = 8
//    var itemAttributes : NSMutableArray!
    var itemAttributes : [[UICollectionViewLayoutAttributes]]!
    //    var itemsSize : NSMutableArray!
    var itemsSize : [CGSize]!
    var contentSize : CGSize!
    var itemHeight:CGFloat = 30
    var itemFont:UIFont = UIFont.systemFontOfSize(17)
    override func prepareLayout() {
        if self.collectionView?.numberOfSections() == 0 {
            return
        }
        if (self.itemAttributes != nil && self.itemAttributes.count > 0) {
            for section in 0..<self.collectionView!.numberOfSections() {
                let numberOfItems : Int = self.collectionView!.numberOfItemsInSection(section)
                for index in 0..<numberOfItems {
                    if section != 0 && index != 0 {
                        continue
                    }
                    let attributes : UICollectionViewLayoutAttributes = self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: section))!
                    if section == 0 {
                        var frame = attributes.frame
                        frame.origin.y = self.collectionView!.contentOffset.y
                        attributes.frame = frame
                    }
                    if index == 0 {
                        var frame = attributes.frame
                        frame.origin.x = self.collectionView!.contentOffset.x
                        attributes.frame = frame
                    }
                }
            }
            return
        }
        if (self.itemsSize == nil || self.itemsSize.count != numberOfColumns) {
            self.calculateItemsSize()
        }
        var column = 0
        var xOffset : CGFloat = 0
        var yOffset : CGFloat = 0
        var contentWidth : CGFloat = 0
        var contentHeight : CGFloat = 0
        for section in 0..<self.collectionView!.numberOfSections() {
            //let sectionAttributes = NSMutableArray()
            var sectionAttributes = [UICollectionViewLayoutAttributes]()
            for index in 0..<numberOfColumns {
                //let itemSize = self.itemsSize[index].CGSizeValue()
                let itemSize = self.itemsSize[index]
                let indexPath = NSIndexPath(forItem: index, inSection: section)
                let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
                attributes.frame = CGRectIntegral(CGRectMake(xOffset, yOffset, itemSize.width, itemSize.height))
                if section == 0 && index == 0 {
                    attributes.zIndex = 1024
                } else  if section == 0 || index == 0 {
                    attributes.zIndex = 1023
                }
                if section == 0 {
                    var frame = attributes.frame
                    frame.origin.y = self.collectionView!.contentOffset.y
                    attributes.frame = frame
                }
                if index == 0 {
                    var frame = attributes.frame
                    frame.origin.x = self.collectionView!.contentOffset.x
                    attributes.frame = frame
                }
                //sectionAttributes.addObject(attributes)
                sectionAttributes.append(attributes)
                xOffset += itemSize.width
                column += 1
                if column == numberOfColumns {
                    if xOffset > contentWidth {
                        contentWidth = xOffset
                    }
                    column = 0
                    xOffset = 0
                    yOffset += itemSize.height
                }
            }
            if (self.itemAttributes == nil) {
                //self.itemAttributes = NSMutableArray(capacity: self.collectionView!.numberOfSections())
//                self.itemAttributes = Array<Array<UICollectionViewLayoutAttributes>>()
//                self.itemAttributes = [[UICollectionViewLayoutAttributes]]()
                //self.itemAttributes = Array<>Array<UICollectionViewLayoutAttributes>(count: self.collectionView!.numberOfSections(), repeatedValue: UICollectionViewLayoutAttributes())
                self.itemAttributes = [[UICollectionViewLayoutAttributes]]()
            }
//            self.itemAttributes.addObject(sectionAttributes)
            self.itemAttributes.append(sectionAttributes)
        }
//        let attributes : UICollectionViewLayoutAttributes = self.itemAttributes.lastObject?.lastObject as! UICollectionViewLayoutAttributes
        let attributes : UICollectionViewLayoutAttributes = self.itemAttributes.last!.last!
        contentHeight = attributes.frame.origin.y + attributes.frame.size.height
        self.contentSize = CGSizeMake(contentWidth, contentHeight)
    }
    override func collectionViewContentSize() -> CGSize {
        return self.contentSize
    }
    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        //return self.itemAttributes[indexPath.section][indexPath.row] as? UICollectionViewLayoutAttributes
//        let sectionAttributes = self.itemAttributes[indexPath.section] as! [UICollectionViewLayoutAttributes]
        let sectionAttributes = self.itemAttributes[indexPath.section]
        return sectionAttributes[indexPath.row] as UICollectionViewLayoutAttributes
    }
    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attributes = [UICollectionViewLayoutAttributes]()
        if self.itemAttributes != nil {
            for section in self.itemAttributes {
//                let filteredArray  =  section.filteredArrayUsingPredicate(
//                    
//                    NSPredicate(block: { (evaluatedObject, bindings) -> Bool in
//                        return CGRectIntersectsRect(rect, evaluatedObject.frame)
//                    })
//                    ) as! [UICollectionViewLayoutAttributes]
//
//                attributes.appendContentsOf(filteredArray)
                let filteredArray  =  section.filter({ (evaluatedObject) -> Bool in
                    return CGRectIntersectsRect(rect, evaluatedObject.frame)
                })
                attributes.appendContentsOf(filteredArray)
            }
        }
        return attributes
    }
    override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
        return true
    }
    func sizeForItemWithColumnIndex(columnIndex: Int) -> CGSize {
        var text : String = ""
        switch (columnIndex) {
        case 0:
            text = "Col 0"
        case 1:
            text = "Col 1"
        case 2:
            text = "Col 2"
        case 3:
            text = "Col 3"
        case 4:
            text = "Col 4"
        case 5:
            text = "Col 5"
        case 6:
            text = "Col 6"
        default:
            text = "Col 7"
        }
//        let size : CGSize = (text as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(17.0)])
        let size : CGSize = (text as NSString).sizeWithAttributes([NSFontAttributeName: self.itemFont])
        let width : CGFloat = size.width + 25
        return CGSizeMake(width, itemHeight)
    }
    func calculateItemsSize() {
//        self.itemsSize = NSMutableArray(capacity: numberOfColumns)
//        for index in 0..<numberOfColumns {
//            self.itemsSize.addObject(NSValue(CGSize: self.sizeForItemWithColumnIndex(index)))
//        }
        self.itemsSize = [CGSize]()
        for index in 0..<numberOfColumns {
            self.itemsSize.append(self.sizeForItemWithColumnIndex(index))
        }
    }
}

效果是:

转载请注明:在路上 » [已解决]swift表格视图 gridview

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
66 queries in 0.215 seconds, using 18.92MB memory