简体   繁体   English

确定用户按下了哪个按钮

[英]Determining which button the user pressed

I would like to have three buttons or images in my view, that each represent a "weapon". 我想在视图中显示三个按钮或图像,每个按钮或图像代表一个“武器”。 How can I know which button has been selected by the user, and use this information? 我如何知道用户选择了哪个按钮,并使用此信息?

I thought I would use one function to collect the information about the weapon selected, its damage, etc., but I'm used to creating one function for each button in the view. 我以为我会使用一个功能来收集有关所选武器及其损坏等的信息,但是我习惯于为视图中的每个按钮创建一个功能。 I'm wondering now how to determine the difference between those buttons, depending on which one has been selected. 我现在想知道如何根据选择的按钮来确定这些按钮之间的差异。

You should create action methods that take one argument, the sender: 您应该创建带有一个参数(发送方)的操作方法:

- (IBAction)weaponPressed:(id)sender;

You can then check the sender against instance variables pertaining to the buttons: 然后,您可以根据与按钮有关的实例变量检查发送者:

if (sender == gunWeaponButton)
    // Do something
else if (sender == mineWeaponButton)
    // Do something
else
    // Do something else

Also, you can assign a tag to the buttons, which is simply an integer value: 另外,您可以为按钮分配标签,它只是一个整数值:

gunWeaponButton.tag = 0;

Then you can check for the sender's tag: 然后,您可以检查发件人的标签:

if (sender.tag == gunWeaponButton.tag)
    // Do something

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM