UITableViewCell.accessoryViewに設定したUIButtonにtintColorを設定する
UITableViewCell
の右側にボタンを配置する際にaccessoryViewを利用すると、ボタンではなくCellを誤タップすることが回避でき大変便利です。
UITableViewCell.accessoryViewにUIButtonを設定する
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
button.setImage(UIImage(systemName: "arrow.up.left")!, for: .normal)
cell.accessoryView = button
このように実装するだけで利用することができます。
tintColorを設定する場合
しかし、このボタンにtintColor
を設定する場合は、UIButton
ではなくUITableViewCell
のtintColor
を設定しないと、端末を回転させた際にtintColor
が戻されてしまうので注意する必用があります。
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
button.setImage(UIImage(systemName: "arrow.up.left")!, for: .normal)
button.tintColor = .label // これは誤り
cell.accessoryView = button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
button.setImage(UIImage(systemName: "arrow.up.left")!, for: .normal)
cell.tintColor = .label // これが正しい
cell.accessoryView = button
UITableViewCellとは異なるtintColorに設定したい場合
UITableViewCell
とは異なるtintColor
に設定したい場合は、UIImage
のRenderingModeを変更することで設定することができます。
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
button.setImage(UIImage(systemName: "arrow.up.left")!.withTintColor(.label, renderingMode: .alwaysOriginal), for: .normal)
cell.tintColor = .systemBlue
cell.accessoryView = button
この記事の挙動は以下のレポジトリから確認することができます.
- https://github.com/soranoba/iOS-SandBox/tree/UITableViewCell.accessoryView.tintColor-automatically-set-nil-when-the-device-rotated
記事が気に入ったらチップを送ることができます!
You can give me a cup of coffee :)
Kyash ID: soranoba
Amazon: Wish List
GitHub Sponsor: github.com/sponsors/soranoba
PayPal.Me: paypal.me/soranoba
(Updated: )