【Swift/Objective-C】iOS13にてUITableViewでデフォルトで採用しているヘッダーのカラーが変更になった話【Xcode11/iOS13】

こういう人に向けて発信しています。
・iOS13対応を行なっている全ての方に向けて
・TableViewセクションヘッダーをカスタムしたい人
・Swift/Objective-C 中級者

実際の変更点

スクリーンショット 2019-10-25 10.08.38

ヘッダーの色が変更されています。

どのように従来の色を再現すれば良いか記載しましたのでご確認ください

用いる方法について

両言語とも下記メソッドを活用します。

//Swift
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

//Objective-C
- (UIView *)tableView:(UITableView *)tableView 
viewForHeaderInSection:(NSInteger)section;

UITableViewのセクションに採用するUIViewを描画するクラスです。
ここでセクションヘッダーに設定したいUIViewを返却してあげてください。

しかしUIViewの色だけを変更してしまっても、
既存のセクションの上に描画されるわけではなく、
返却されたUIViewだけ描画されるので、
文字情報はありません。

なので返却するUIviewにはUILabelも共に描画してあげましょう。

Swift

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
       return "セクション"
   }   

 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
       let sectionLabel = UILabel()
       sectionLabel.frame = CGRect(x:20,y:0,width:320,height:20)
       sectionLabel.font = UIFont.systemFont(ofSize: 16.0)
       sectionLabel.text? = self.tableView(self.tableView, titleForHeaderInSection: section)!
       
       let headerView = UIView()
       headerView.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1.0)
       headerView.addSubview(sectionLabel)
       
       return headerView
   }

Objective-C

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"String"
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

   UILabel *myLabel = [[UILabel alloc] init];
   myLabel.frame = CGRectMake(20, 0, 320, 20);
   myLabel.font = [UIFont boldSystemFontOfSize:16];
   myLabel.text = [self tableView:tableView titleForHeaderInSection:section];

   UIView *headerView = [[UIView alloc] init];
   headerView.backgroundColor = RGBA(247, 247, 247, 1.0);
   [headerView addSubview:myLabel];

   return headerView;

}

実際にビルドしてみた。

こちらが変更前です。

画像2

変更後です。



画像3

若干薄くしております。



この記事が気に入ったらサポートをしてみませんか?