2014-09-25 41 views
0

我有動態單元的UITableView。在viewDidLoad我有NSURLSession下載一些數據到公用變量someDataArray: [NSString]。我在我的單元格中使用AutoLayout和UILabel具有約束條件,如this。當視圖加載時,我想看到所有的單元格大小相同(例如:100)。但是,當細胞被竊聽我想改變這種細胞的高度,以高度的尺寸UIlabel框架 的所以我的代碼如下所示:來自NSURLSession的動態數據的單元行高度

class someVC: UIViewController, UITableViewDelegate 
{ 
    var someDataArray: [NSString] = [] 
    var cellTapped = 0 

    override func viewDidLoad() { 
    //NSURLSession download to someDataArray[] 
    } 

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! 
    { 
    let cell = self.table.cellForRowAtIndexPath(indexPath) as customCellVC 
    cell.someTextView.text = someDataArray[indexPath.row] 
    } 

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let cell = self.table.cellForRowAtIndexPath(indexPath) as customCellVC 

     if(cellTapped == 0) { 
     cellTapped = 1 
     table.beginUpdates() 
     table.endUpdates() 
     } else { 
     cellTapped = 0 
     table.beginUpdates() 
     table.endUpdates() 
     } 
    } 

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

    // heightForRowAtIndexPath call first, how to calculate the size of frame uilabel? When it's tapped or not 
    // how to make all UILabel one size by load but sizetofit by tap on it? 
} 
} 

回答

1

你可以使用自動佈局來計算行的高度。看看這個:

https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8

或者:(所以我解決了這一點,因爲它更貼近我的要求)是:

計算高度的標籤:

func getLabelHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat { 

    let font = UIFont.systemFontOfSize(fontSize) 
    let size = CGSizeMake(width,CGFloat.max) 
    let paragraphStyle = NSMutableParagraphStyle() 
    paragraphStyle.lineBreakMode = .ByWordWrapping; 
    let attributes = [NSFontAttributeName:font, 
     NSParagraphStyleAttributeName:paragraphStyle.copy()] 

    var text = mytext as NSString 
    let rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil) 
    return rect.size.height 
} 

這將返回一個特定寬度的標籤的計算高度。你可以在ViewDidLoad上計算這個值(第一次,並將其設置爲一個以Indexpath.row爲索引的Dictionary),然後使用這個值作爲「heightForRowAtIndexPath」。所以你也可以重新加載你的特定單元格(用你的新高度)

然後你仍然可以使用「SizeToFit」寬度來指定特定的標籤寬度。

+0

感謝這個功能。我會嘗試並讓你知道 – 2014-09-25 11:52:35

+0

當你只使用「sizeToFit」時要小心 - 因爲它默認不會在你的框架中使用給定的寬度。您還應該將標籤的框架設置爲計算出的高度。 – derdida 2014-09-25 11:57:35

相關問題