Can a standard accessory view be in a different position within a UITableViewCell?

前端 未结 11 1101
谎友^
谎友^ 2020-12-05 09:57

I want my accessory to be in a slightly different place than normal. Is it possible? This code has no effect:

cell.accessoryType =  UITableViewCellAccessoryD         


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 10:38

    improvements on other answers

    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.

    solution for Swift 3.x and 4.0

    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
            }
        }
    }
    

    for Swift 4.1 and newer

    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
            }
        }
    }
    

提交回复
热议问题