如何制作UITableViewCell

时间:2015-09-08 03:27:40

标签: ios swift uitableview autolayout

我想根据表格单元格内容创建UITableViewCell的动态高度。

但我不能。

import UIKit


    class WorkItemCell: UITableViewCell{


        @IBOutlet weak var item_view: UIView!
        @IBOutlet weak var minimum_startday_label: CustomLabel!
        @IBOutlet weak var catchcopyLabel: CustomLabel!
        @IBOutlet weak var stationLabel: UILabel!
        @IBOutlet weak var paymentLabel: UILabel!
        @IBOutlet weak var limitLabel: UILabel!
        @IBOutlet weak var mainjobLabel: UILabel!
        @IBOutlet weak var companyLabel: UILabel!

        @IBOutlet weak var workstartdateLabel2: UILabel!

        @IBOutlet weak var fav_view: ImageWithView!
        @IBOutlet weak var img_seen_view: UIImageView!

        override func awakeFromNib() {
            super.awakeFromNib()

            //self.fav_view = ImageWithView.instance()

            self.fav_view.checkedImage = UIImage(named: "fav_on")
            self.fav_view.uncheckedImage = UIImage(named: "fav_off")


        }

        override func layoutSubviews() {
            super.layoutSubviews()
            self.contentView.layoutIfNeeded()
            self.catchcopyLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.catchcopyLabel.bounds)

        }


        private var _workdic: NSDictionary?
        var workdic: NSDictionary? {
            get {
                return _workdic
            }
            set(workdic) {
                _workdic = workdic
                if let workdic = workdic {

                    let workplace = workdic["WorkPlace"] as? String
                    let companyname = workdic["CompanyName"] as? String
                    let jobname = workdic["JobName"] as? String
                    let payment = workdic["Payment"] as? String
                    let workstartdate = workdic["WorkStartDate"] as? String
                    let workdatetime = workdic["WorkDateTime"] as? String
                    let minimumday = workdic["MinimumWorkDay"] as? String
                    let applyenddate = workdic["ApplyEndDate"] as? String
                    let catchcopy = workdic["CatchCopy"] as? String


                    if notnullCheck(catchcopy){
                        //行間
                        let attributedText = NSMutableAttributedString(string: catchcopy!)
                        let paragraphStyle = NSMutableParagraphStyle()
                        paragraphStyle.lineSpacing = 5
                        paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
                        attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedText.length))
                        self.catchcopyLabel.attributedText = attributedText
                    }
                    self.catchcopyLabel.sizeToFit()

                    if let payment_constant = payment{
                        self.paymentLabel.text = payment_constant
                    }

                    if notnullCheck(minimumday) && notnullCheck(workstartdate){
                        self.minimum_startday_label.text = minimumday!+" "+workstartdate!

                    }else{
                        self.minimum_startday_label.text = ""
                    }
                    if let applyenddate_constant = applyenddate{
                        self.limitLabel.text = applyenddate_constant
                    }

                    if let jobname_constant = jobname{
                        self.mainjobLabel.text = jobname_constant
                    }


                    if let workdatetime_constant = workdatetime{
                        self.workstartdateLabel2.text = workdatetime_constant
                    }


                    if let companyname_constant = companyname{
                        self.companyLabel.text = companyname_constant
                    }

                    self.stationLabel.text = workplace
                    self.item_view.sizeToFit()

                }
            }
        }

        class func heightForRow(tableView: UITableView, workdic: NSDictionary?) -> CGFloat {
            struct Sizing {
                static var cell: WorkItemCell?
            }
            if Sizing.cell == nil {
                Sizing.cell = tableView.dequeueReusableCellWithIdentifier("WorkItemCell") as? WorkItemCell
            }
            if let cell = Sizing.cell {
                cell.frame.size.width = CGRectGetWidth(tableView.bounds)
                cell.workdic = workdic
                cell.setNeedsDisplay()
                cell.layoutIfNeeded()

                let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
                print(size)
                return size.height+1
            }
            return 0
        }

    }

以上代码有item_view。 它具有所有标签和图像。 设定边距为4点(上,左,下,右),5px。

我使用上面的单元格作为数据列表。 它有大约5000个计数。

Catch copy label经常设置2行句。 我想更改每个catch_copy_label高度的item_view高度和单元格高度。

但我无法做到。 我总是得到相同的高度,26px。

(366.5, 26.0)
(366.5, 26.0)

我该怎么办?

我添加了视图控制器的源代码部分。

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{


    if self.int_total == 0{
        return self.view.frame.size.height
    }else{
        if let workdic: AnyObject = workdata.safeObjectAtIndex(indexPath.row){

            return WorkItemCell.heightForRow(self.workview, workdic: (workdic as! NSDictionary),base_height:170)

        }else{
            return 199
        }

    }



}

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 199
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


    if self.int_total == 0{
        return 1

    }
    return self.workdata.count

}



/*
Cellに値を設定する.
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // Cellの.を取得する.
    if self.int_total > 0{



        let cell = workItemCell(tableView, cellForRowAtIndexPath: indexPath, str_xib: "WorkItemCell")
        return cell

    }else{
        let nocell: NoCountCell = tableView.dequeueReusableCellWithIdentifier("NoCountCell", forIndexPath: indexPath) as! NoCountCell
        nocell.conditionButton.addTarget(self, action: "onClickBack:", forControlEvents: .TouchUpInside)

        //初期が終わったらfalse
        if self.init_loading{
            nocell.conditionButton.hidden = true
            nocell.messageLabel.hidden = true
        }else{
            nocell.conditionButton.hidden = true
            nocell.messageLabel.hidden = false
        }
        return nocell
    }

}
func workItemCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath,str_xib:String) ->WorkItemCell{
    let wcell: WorkItemCell = tableView.dequeueReusableCellWithIdentifier(str_xib, forIndexPath: indexPath) as! WorkItemCell
    wcell.separatorInset = UIEdgeInsetsZero
    wcell.selectionStyle = UITableViewCellSelectionStyle.None
    updateCell(wcell, atIndexPath: indexPath)

    return wcell
}

func updateCell(cell:UITableViewCell,atIndexPath:NSIndexPath){

}


func showWorkItem(wcell:WorkItemCell,workdic:NSDictionary){



    wcell.workdic = workdic

}

我发布了捕获。 enter image description here

3 个答案:

答案 0 :(得分:0)

这是在Objective C.Calculate .state('exam', { url: '/exam/:step', abstract: true, // the root view and the static pagination view // will be defined here, so we need views : {} views: { '':{ templateUrl: 'app/state-exam/exam.html', controller: 'ExamController', controllerAs: 'examController', }, // absolute naming targets the view defined above 'exam-pagination@exam':{ templateUrl: 'app/state-exam/exam-pagination.html' }, } }) .state('exam.instructions', { url: '/instructions', views: { // 'exam-pagination':{}, // defined in parent 'exam-detail' : { templateUrl: 'app/state-exam/exam-instructions.html' } } }) .state('exam.math', { url: '/math', views: { // 'exam-pagination':{}, // defined in parent 'exam-detail' : { templateUrl: 'app/state-exam/exam-math.html' } } }); 方法中单元格内容的高度将其添加到一个数组中

heightForRowAtIndexPath

现在在- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath { text =[NSString stringWithFormat:@"%@",[content_array objectAtIndex:indexPath.row]]; CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tblView.frame.size.width - PADDING * 3, 1000.0f)]; NSLog(@"%f",textSize.height); [height_Array addObject:[NSString stringWithFormat:@"%f", textSize.height]]; return textSize.height; } 方法中,使用高度数组将标题框设置为: -

cellForRowAtIndexPath

答案 1 :(得分:0)

答案 2 :(得分:0)

我最终得到了答案。 但我手动计算了身高。

我每次计算标签的高度。 这个标签有多行。 然后我设置高度其他高度+计算的高度。

class func heightForCatchCopy(tableView: UITableView, workdic: NSDictionary?) -> CGFloat {
    struct Sizing {
        static var cell: WorkItemCell?
    }
    if Sizing.cell == nil {
        Sizing.cell = tableView.dequeueReusableCellWithIdentifier("WorkItemCell") as? WorkItemCell
    }
    if let cell = Sizing.cell {
        cell.frame.size.width = CGRectGetWidth(tableView.bounds)
        cell.workdic = workdic

        let size = cell.catchcopyLabel.intrinsicContentSize()
        return size.height
    }
    return 0
}