LoginSignup
11
5

More than 3 years have passed since last update.

【Swift】TableViewのセクションの色を変更する

Posted at

やりたいこと

Screenshot 2019-11-02_00-16-14-502.png

これを...

Screenshot 2019-11-02_00-15-34-522.png

こうしたい

やりかた

    // セクションの背景とテキストの色を変更する
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        // 背景色を変更する
        view.tintColor = .red

        let header = view as! UITableViewHeaderFooterView
        // テキスト色を変更する
        header.textLabel?.textColor = .white
    }

おまけ

セクションごとに背景とテキストの色を変更したい

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        // switch文でsectionごとに色を変更する
        switch section {
        case 0:
            view.tintColor = .green
            let header = view as! UITableViewHeaderFooterView
            header.textLabel?.textColor = .yellow

        case 1:
            view.tintColor = .red
            let header = view as! UITableViewHeaderFooterView
            header.textLabel?.textColor = .white

        default:
            view.tintColor = .lightGray
            let header = view as! UITableViewHeaderFooterView
            header.textLabel?.textColor = .blue
        }
    }


11
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5