Keeping a UIButton selected after a touch

后端 未结 9 1456
后悔当初
后悔当初 2020-11-27 11:41

After my user clicks a button, I\'d like that button to stay pushed during the time that I perform a network operation. When the network operation is complete, I want the bu

9条回答
  •  佛祖请我去吃肉
    2020-11-27 12:34

    In swift I'm doing it like the following.

    I create a Subclass of UIButton and implemented a custom property state

    class ActiveButton: UIButton {
    
        private var _active = false
        var active:Bool {
            set{
                _active = newValue
                updateState()
            }
            get{
                return _active
            }
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.addTarget(self, action: #selector(ActiveButton.touchUpInside(_:)), forControlEvents: .TouchUpInside)
        }
    
        func touchUpInside(sender:UIButton) {
            active = !active
        }
    
        private func updateState() {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                self.highlighted = self.active
            }
        }
    
    }
    

    Works perfectly for me.

提交回复
热议问题