Prateekro Prateekro - 3 years ago 158
Swift Question

UIButton text not visible when animating button image

I have to toggle two images (with animation) on UIButton, but that hides my label behind image on UIButton. Hence I added subview of UILabel to it and that is also not showing. I even tried to bring the subview to the front but that also doesn't work.

let options = [option_1, option_2, option_6]
var imageArray = [UIImage]()

imageArray.append( UIImage(named: "light_button.png" )! )
imageArray.append( UIImage(named: "dark_button.png" )! )

let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.option_1.frame.width, height: self.option_1.frame.width))
label.text = "HEY"
label.font = UIFont.systemFont(ofSize: 18)
option_1.addSubview(label)
option_1.bringSubview(toFront: label)

for option in options{
option?.setImage( UIImage(named: "green_button.png")!, for: .normal)

option?.imageView!.animationImages = imageArray
option?.imageView!.animationImages = imageArray

option?.setTitle("TEST TEXT", for: .normal) //Even this don't work

option?.imageView!.animationDuration = 2.35
option?.imageView!.startAnimating()
}


What's wrong?

Answer Source

I will try to give you a simple solution. Take a button and adjust its selected and default state from storyboard itself. For example select the default state of a button and give it a title and and image from the IBInspector.Then repeat the same process for selected state as well choosing the state configurations. enter image description here

Then you can also manage the image and title of the button as shown in the image.enter image description here

Then at at last you can manage your code as given below:

       class ViewController: UIViewController {
    @IBOutlet weak var buttonObj: UIButton!
   var stop = false
    var timer:Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
       // toggleButtons()
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.toggleButtons), userInfo: nil, repeats: true);
    }

    func toggleButtons(){
        if stop{
            timer?.invalidate()
        }else{
            buttonObj.toggleSelection()
        }


    }

      @IBAction func btnClicked(_ sender: Any) {

        //Once you click the button stop will become true and hence your timer will invalidate
        stop = true
    }
}
    //MARK:-******** UIButtonExtension  ***********
extension UIButton {
    func toggleSelection() {
        self.selected = self.selected ? false : true
    }
}

You can also choose between various animation types as per your requirement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download