当动画按钮图像时,UIButton文本不可见

当动画按钮图像时,UIButton文本不可见

问题描述:

我必须在UIButton上切换两个图像(带动画),但在UIButton上隐藏了我的标签。因此,我添加了UILabel的子视图,但这也没有显示出来。我甚至试图把子视图放到前面,但这也不起作用。当动画按钮图像时,UIButton文本不可见

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

怎么了?

+0

你在选项数组中添加了什么? – Ishika

+0

@ishika那些是UIButtons。 – Prateekro

+0

我的意思是问你有没有编程创建插座或创建按钮? – Ishika

我会尽量给你一个简单的解决方案。 采取一个按钮,并从故事板本身调整其选定和默认状态。例如,选择一个按钮的默认状态,并从IBInspector给它一个标题和图像。然后重复选择状态的相同过程以及选择状态配置。 enter image description here

然后,您还可以管理图像中显示的按钮的图像和标题。

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

您也可以将各种动画类型按您的要求进行选择:enter image description here

然后在最后下面给出你可以管理你的代码。

+0

随着我从另一个角度进入观点。我希望视图能够像闪烁灯泡一样启动按钮。 (切换2张图像。)上述解决方案可行吗? – Prateekro

+0

我希望循环切换继续,直到有一个点击。在任何选项上。 – Prateekro

+0

哦,这个作品很有魅力。我做了必要的修改以满足我的要求。 – Prateekro

您是否尝试将图片设置为背景图片? ?

选项.setBackgroundImage(的UIImage(命名为:“green_button.png”)!为:。中性)

+0

是的。 @kathiria,但它不适用于动画 – Prateekro

状态之间切换时,您可以设置UIButton的背景图像对正常和选中状态,然后动画(切换选择,并没有选择按钮的水龙头)

+0

但我想不出任何方式来动画背景图像。 你能介意吗。为它提供和编写框架。提前致谢。 – Prateekro