简体   繁体   English

根据另一个变量设置按钮图像? 迅速

[英]Setting a button image depending on another variable? Swift

so I'm very new to swift. 所以我很新。 I currently have 16 buttons all set to individual outlets box1,box2,box3 etc. 我目前有16个按钮,分别设置为单独的插座box1,box2,box3等。

Each box I have set a tag and what I am trying to do is set the image of a particular box based off another integer variable to determine which box I'm changing. 我为每个盒子设置了一个标签,我要做的是根据另一个整数变量设置特定盒子的图像,以确定我要更改哪个盒子。

So say I do a calculation and index = 4. Is there a way I can then set box(index).setImage? 因此,说我进行了计算并且index =4。有没有办法设置box(index).setImage?

I understand this probably isn't the best way to do it or even possible, maybe I can set each button to an array of objects instead? 我知道这可能不是最好的方法,甚至可能,也许我可以将每个按钮设置为对象数组? Any tips would be great. 任何提示都很好。

If you want to set the image of button through some tag then you don't need any outlets for the buttons. 如果要通过某个标签设置按钮的图像,则按钮不需要任何插座。

You can change your button image by finding the button through viewWithTag() property. 您可以通过viewWithTag()属性找到按钮来更改按钮图像。

Here is the code 这是代码

var button = self.view.viewWithTag(Your_Calculated_Index) as! UIButton
button.setImage(Your_Image, for: .normal)

You can try this. 你可以试试看 You need to create an array for the button. 您需要为按钮创建一个数组。

@IBOutlet var allbtns: [UIButton]!

for buttons in allbtns{
    if buttons.tag == 4{
        print("Button 4 ");
        buttons.setImage(UIImage(named: "imagname"), for: UIControlState.normal)
    }else{
        print("Other buttons except 4 ");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据变量在SWIFT中更改图像,单击使用IF语句的按钮 - How to change an image in SWIFT depending on a variable, clicking a button that uses an IF statement 将图像设置为全局变量(在Swift中) - Setting an image as a global variable (in Swift) Swift 3-在TableViewController swift文件中设置变量,具体取决于单击的单元格 - Swift 3 - Setting variable in TableViewController swift file depending on cell clicked swift:在导航栏中设置按钮图像 - swift: setting back button image in nav bar 快速将图像设置为按钮,单击力度太大 - Swift setting image as button, clicking too hard 根据Swift xCode中的变量将UI图像更改为特定图像 - Changing UI Image to a specific image depending on variable in Swift xCode 是否可以根据 class 中的另一个变量初始化变量,该变量继承自 Swift 中的 UIViewController? - Is it possible to initialize variable depending on another in class inheriting from UIViewController in Swift? 以编程方式将条形按钮项图像设置为系统项—Swift - Setting bar button item image to system item programmatically—Swift 设置导航栏后退按钮快速显示整个应用程序的图像 - Setting Navigation bar back button Image for entire application in swift 单击图像不会改变,直到我迅速单击另一个按钮 - Button image not changing on clicking until i click on another button in swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM