2016-07-01 42 views
4

我正在使用Xib文件而不是故事板。我用一些虛擬數據創建了一個表格視圖。它的工作正常,現在我已經創建了一些帶有一些標籤和textFields的自定義單元格。我怎樣才能使用它作爲UITableView的頁眉或頁腳?如何將自定義單元格設置爲UITableView的頁眉或頁腳

+0

不能使用的UITableView細胞作爲頁眉或頁腳,對於您需要創建一個視圖(廈門國際銀行),你可以用它 –

+0

細胞作爲標題? tableHeaderView是一種視圖,而不是單元格 – ronan

+0

如何使用和Xib創建UiView?當我創建一個新的CocoaTouch文件,並使其UIView的子類的「也創建Xib文件」的選項不能檢查 – Byte

回答

1

您可以編程方式創建自定義視圖。我試了下面的代碼。嘗試一次。

override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { 
     let customview:UIView = UIView(); 
     let label = UILabel(); 
     label.text = "ur custom data" 
     /* 
      You can add any number of subviews you want here 
      And don't forget to add it to your customview. 
     */ 
     customview.addSubview(label) 
     return customview; 
    } 

同樣,你也可以爲標題做同樣的事情。

1

這是方法添加TableView的標題: 在那你可以任何控制像UIButton,UIImageView,....等。

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
     let sectionView = UIView() 
     sectionView.frame = CGRectMake(x,y,height,width) // For Set the Frame 
     sectionView.backgroundColor = UIColor.redColor() 

     return sectionView 
    } 
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { 
     let sectionView = UIView() 
     sectionView.frame = CGRectMake(x,y,height,width) // For Set the Frame 
     sectionView.backgroundColor = UIColor.redColor() 

     return sectionView 
    } 

像上面你可以設置部分的頁腳和 您可以添加標題的大小和頁腳

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 20.0 
} 

func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { 
    return 20.0 
} 
+0

我創建了一個包含imageView的cstom視圖。當我嘗試使用這種方法與一個簡單的視圖wotha nackground顏色它的作品,但不是與我的自定義視圖 – Byte

14

其實答案很簡單。 在viewForHeaderInSection()中創建單元格對象,如您在cellForRowAtIndexPath()中所做的那樣並將其返回。

以下是示例代碼。

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") as! YourTableViewCell 
    return cell 
} 

您可以爲標題的設置高度:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 80 
}