How to use a UIButton as a toggle switch

前端 未结 11 766
我在风中等你
我在风中等你 2020-12-02 18:44

I am using a UIButton of custom type and what I want is use it like a toggle switch with the change of image. Like when it is clicked if previously it was not in selected mo

11条回答
  •  抹茶落季
    2020-12-02 19:06

    In order to do so we can use UIButton Subclass:

    class UIToggleButton: UIButton {
        fileprivate let onImage: UIImage
        fileprivate let offImage: UIImage
        fileprivate let target: AnyObject
        fileprivate let onAction: Selector
        fileprivate let offAction: Selector
        var isOn: Bool {
            didSet {
                let image = isOn ? onImage : offImage
                setImage(image, for: UIControlState())
            }
        }
    
        init(onImage: UIImage,
            offImage: UIImage,
            target: AnyObject,
            onAction: Selector,
            offAction: Selector)
        {
            isOn = false
            self.onImage = onImage
            self.offImage = offImage
            self.target = target
            self.onAction = onAction
            self.offAction = offAction
            super.init(frame: CGRect.zero)
            setImage(offImage, for: UIControlState())
            addTarget(self, action: #selector(UIToggleButton.tapAction), for: .touchUpInside)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        @objc func tapAction() {
            let sel = isOn ? onAction : offAction
            isOn = !isOn
            _ = target.perform(sel)
        }
    }
    

提交回复
热议问题