I want my accessory to be in a slightly different place than normal. Is it possible? This code has no effect:
cell.accessoryType = UITableViewCellAccessoryD
For James Kuang, Kappe, accessoryView is nil for default accessory view.
For Matjan, subviews.lastObject is easily the wrong view, like an UITableViewCellSeparatorView.
For Alexey, Ana, Tomasz, enumerating the subviews until we find an unknown one works for now. But it's laborious and could be easily broken in future versions if, let say, Apple adds a backgroundAccessoryView.
For larshaeuser, enumerating the subviews until we find a UIButton is good idea, but contentEdgeInsets is not adequately visibly changing the accessory view.
We will enumerate and look for the last UIButton.
class AccessoryTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
if let lastButton = subviews.reversed().lazy.flatMap({ $0 as? UIButton }).first {
// This subview should be the accessory view, change its origin
lastButton.frame.origin.x = bounds.size.width - lastButton.frame.size.width - 5
}
}
}
class AccessoryTableViewCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
// https://stackoverflow.com/a/45625959/1033581
if let lastButton = subviews.reversed().lazy.compactMap({ $0 as? UIButton }).first {
// This subview should be the accessory view, change its origin
lastButton.frame.origin.x = bounds.size.width - lastButton.frame.size.width - 5
}
}
}