2014-11-19 13 views
7

Tôi muốn nhận Tiêu đề của Tiêu đề trong phần của UITableView, Vui lòng hướng dẫn tôi cú pháp trong số swift để nhận Tiêu đề của Tiêu đề trong phần là gì.UITableView có được tiêu đềĐối vớiHeadersInSection swift

func tableView(tableView : UITableView, titleForHeaderInSection section: Int)->String 
{ 
    switch(section) 
    { 
    case 2:return "Title 2" 
     break 
    default :return "" 
     break 
    } 

} 

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

var title = tableView.titleForHeaderInSection[section]; 
if (title == "") { 
return 0.0; 
} 
return 20.0; 
} 

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

var title = tableView.titleForHeaderInSection[section] as String 
if (title == "") { 
return UIView(frame:CGRectZero); 
} 
var headerView:UIView! = UIView (frame:CGRectMake(0, 0, self.tableView.frame.size.width, 20.0)); 
headerView.backgroundColor = self.view.backgroundColor; 

return headerView; 
} 
+0

Tại sao bạn không sử dụng số phần để so sánh thay vì tiêu đề? – zisoft

+0

thực sự tôi muốn biết cú pháp để có được tiêu đề Đối với tiêu đề trong phần. –

Trả lời

3

Để gọi phương thức này, bạn phải sử dụng phương thức UITableViews titleForHeaderInSection. Phương thức này sẽ cung cấp chỉ mục cho phần hiện tại và bạn được yêu cầu trả về một String, String được trả về sẽ được đặt làm tiêu đề.

Để gọi này, cho phép giả sử chúng ta có một mảng của Strings gọi cars

cars = ["Muscle", "Sport", "Classic"] 

Sau đó chúng tôi có thể chỉ cần gọi

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
{ 
    // Ensure that this is a safe cast 
    if let carsArray = cars as? [String] 
    { 
     return carsArray[section] 
    } 

    // This should never happen, but is a fail safe 
    return "unknown" 
} 

này sẽ trở lại đề mục theo thứ tự đưa ra ở trên.

11

Bạn có thể sử dụng Func đã được xác định trong ví dụ lớp học của bạn:

self.tableView (tableView, titleForHeaderInSection: phần)

Ví dụ, sử dụng mã của bạn:

func tableView(tableView : UITableView, titleForHeaderInSection section: Int)->String { 
    switch(section) { 
    case 2:return "Title 2" 

    default :return "" 

    } 
} 

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

    var title = self.tableView(tableView, titleForHeaderInSection: section) 
    if (title == "") { 
     return 0.0 
    } 
    return 20.0 
} 
+0

Cảm ơn. BTW, bạn không cần "phá vỡ". –

+1

Đã xóa 'ngắt - còn lại từ một đoạn cắt và dán một đoạn mã lớn hơn :) – HungryArthur

Các vấn đề liên quan