2016-11-05 22 views
2

我有這個tableView這裏:TableView Section Header Example的TableView區間變化頭校準

與我想更改爲正確的文本對齊的默認左文本對齊方式。我怎樣才能做到這一點 ?

編輯:

現在看起來是這樣的: How It Looks Now

+0

你用斯威夫特2個或3個工作? –

+0

@GeorgeH斯威夫特2.3 –

+0

@GeorgeH我有一些奇怪的間距問題,你可以嘗試和幫助我嗎? –

回答

2

你必須爲此在UITableView的數據源方法viewForHeaderInSection

雨燕2.3:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let headerText = UILabel() 
    headerText.textColor = UIColor.lightGrayColor() 
    headerText.adjustsFontSizeToFitWidth = true 
    switch section{ 
    case 0: 
     headerText.textAlignment = .Center 
     headerText.text = "This Header Will Be Centered" 
    case 1: 
     headerText.textAlignment = .Right 
     headerText.text = "This Header Will Be Aligned Right" 
    default: 
     headerText.textAlignment = .Left 
     headerText.text = "Default Will Be Left" 
    } 

    return headerText 
} 

編輯:修改了上面的代碼。您可以使用section參數來標識要修改的部分。

+0

我得到這個錯誤:致命錯誤:意外地發現零,同時展開一個可選值 –

+0

只是更新的代碼。 –

+0

它部分工作...現在我的所有部分都有該標題文本,但我想只在其中一些標題文本中,並自定義文本以及它們中的每一個。 +我想要我的原始灰色,如果我可以問:D –

4

斯威夫特4

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return "Your Header Name" 
} 

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
    let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView 
    header.textLabel?.font = UIFont(name: "YourFontname", size: 14.0) 
    header.textLabel?.textAlignment = NSTextAlignment.right 
} 
+1

它完美地工作! IMO比標記的答案更好 –