Keeping a UIButton selected after a touch

后端 未结 9 1311
后悔当初
后悔当初 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:31

    "Everything gets better when you turn power on"

        button.selected = !button.selected;
    

    works perfectly... after I connected the outlet to the button in the Interface Builder.

    You do not need to setBackgroundImage:forState:, the builder allows you to specify the background (gets resized if necessary) or/and foreground (not resizing) images.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 12:39

    I have an easier way. Just use "performSelector" with 0 delay to perform [button setHighlighted:YES] . This will perform re-highlighting after the current runloop ends.

    - (IBAction)buttonSelected:(UIButton*)sender {
        NSLog(@"selected %@",sender.titleLabel.text);
        [self performSelector:@selector(doHighlight:) withObject:sender afterDelay:0];
    }
    
    - (void)doHighlight:(UIButton*)b {
        [b setHighlighted:YES];
    }
    
    0 讨论(0)
提交回复
热议问题