简体   繁体   English

定位以编程方式创建的UIButton

[英]Targeting programmatically created UIButton

Question: How do I target one of many dynamically created UIButtons so I can change its properties? 问题:如何定位许多动态创建的UIButton之一,以便可以更改其属性?

Background: I have a storyboard with a UIViewConroller. 背景:我有一个带有UIViewConroller的情节提要。 When this UIVC loads a UIScrollView is added, to which a UIImageView is placed that has an exhibition floor plan. 当该UIVC加载时,将添加一个UIScrollView,并在其中放置一个具有展览平面图的UIImageView。 Each exhibitor has an entry in a database that contains its location on the floor plan. 每个参展商在数据库中都有一个条目,其中包含其在平面图上的位置。 When the UIVC is loaded a loop is run for all exhibitors and each one has a UIButton drawn on the UIIV. 加载UIVC后,将为所有参展商运行一个循环,每个参展商都有一个绘制在UIIV上的UIButton。 When a UIB is clicked the button background colour is changed (to confirm which exhibitor has been selected) and a UIAlertView is shown with information about that exhibitor. 单击UIB时,按钮的背景色将更改(以确认已选择了哪个参展商),并显示带有该参展商信息的UIAlertView。 When the UIAV's 'cancel' (ok) button is pressed the UIAV closes and the background highlight colour that was applied previously should be removed but here is where I am having the problem. 当按下UIAV的“取消”(确定)按钮时,UIAV关闭,并且应该删除以前应用的背景突出显示颜色,但这是我遇到的问题。 I am unable to target the UIButton so I can change its background colour. 我无法定位UIButton,因此可以更改其背景颜色。

What I have tried so far: As each button is created I am giving it a tag and a title and recording both in an array. 到目前为止,我已经尝试过:在创建每个按钮时,我给它一个标签和一个标题,并将它们记录在一个数组中。 When the 'cancel' button is pressed on the UIAlertView I have tried checking the tag in the array but I still cannot actually target the UIButton. 当在UIAlertView上按下“取消”按钮时,我尝试检查数组中的标签,但实际上仍然无法定位UIButton。

I was thinking something like this: 我在想这样的事情:

// obviously not correct syntax but the kind of thing I want
[exhibitorBtn(tag) setBackgroundColor:[UIColor greenColor]];

So, say I have 12 UIButtons all called exhibitorBtn but with different titles and tags: 因此,假设我有12个UIButtons,都称为ExhibitorBtn,但具有不同的标题和标签:

  • Object ----- Name ---------- Title -------- Tag 对象-----名称----------标题--------标记

  • UIButton -- exhibitorBtn -- Glaxo ------ 1 UIButton-参展商Btn-葛兰素------ 1

  • UIButton -- exhibitorBtn -- Porsche --- 2 UIButton-参展商Btn-保时捷--- 2

  • UIButton -- exhibitorBtn -- Rolex ------- 3 < How would I target that button's properties? UIButton-ExhibitionorBtn-Rolex ------- 3 <我将如何定位该按钮的属性?

Edit - added the code that creates the buttons just to clarify: 编辑-添加了创建按钮的代码,以阐明以下内容:

 for (NSDictionary *dict in exhibitorStandArray) {

    NSInteger currentPosition = [exhibitorStandArray indexOfObject:dict];
    NSLog(@"Position in array = %li", (long)currentPosition);
    if (![dict[@"locCoords"] isEqual: @""]) {

        NSInteger buttonTag = [exhibitorStandArray indexOfObject:dict];
        NSString *standNo = dict[@"locStandNo"];
        NSMutableDictionary *buttonDictionary = [[NSMutableDictionary alloc] init];
        [buttonDictionary setObject:[NSNumber numberWithInteger:buttonTag] forKey:@"buttonTag"];
        [buttonDictionary setObject:standNo forKey:@"buttonStandNo"];

        [_masterButtonList addObject:buttonDictionary];

        NSString *locCoords = dict[@"locCoords"];
        NSArray *tempArray =[locCoords componentsSeparatedByString:@","];
        tlcTop = [[tempArray objectAtIndex:0] integerValue];
        tlcLeft = [[tempArray objectAtIndex:1] integerValue];
        brcTop = [[tempArray objectAtIndex:2] integerValue];
        brcRight = [[tempArray objectAtIndex:3] integerValue];
        buttonWidth = brcRight - tlcLeft;
        buttonHeight = brcTop - tlcTop;

        testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        testBtn.frame = CGRectMake(tlcTop, tlcLeft, buttonHeight, buttonWidth);
        testBtn.titleLabel.text = standNo;
        testBtn.tag = buttonTag;
        NSLog(@"UIButton Title = %@", testBtn.titleLabel.text);
        NSLog(@"UIButton Tag = %li", (long)testBtn.tag);

        testBtn.titleLabel.hidden = YES;

        [testBtn addTarget:self action:@selector(displayInfo:) forControlEvents:UIControlEventTouchUpInside];

        [_buttonArray addObject:testBtn];
        [_imageView addSubview:testBtn];
     }   
}

为什么不能只使用viewWithTag:

    UIButton * button = (UIButton *)[self.scrollView viewWithTag:tag];

Your code probably looks something like this: 您的代码可能看起来像这样:

for (int i = 0; i < 5; i++)
{
    UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
    exhibitorButton.tag = i;
    [scrollView addSubview:exhibitorBtn];
}

Just change the loop so every button will be added to an array, too. 只需更改循环,即可将每个按钮也添加到数组中。 Declare a NSMutableArray as a property: @property (strong, nonatomic) NSMutableArray *buttonsArray; NSMutableArray声明为属性: @property (strong, nonatomic) NSMutableArray *buttonsArray;

And @synthesize and initialise it in your init method. 然后@synthesize并在您的init方法中对其进行初始化。 buttonsArray = [[NSMutableArray alloc] init]

Then, change the loop like I said above: 然后,像上面所说的那样更改循环:

for (int i = 0; i < 5; i++)
{
    UIButton *exhibitorBtn = [[UIButton alloc] initWithFrame:etc..];
    exhibitorButton.tag = i;
    [buttonsArray addObject:exhibitorBtn];
    [scrollView addSubview:exhibitorBtn];
}

Finally, when you want to access the buttons: 最后,当您要访问按钮时:

for (int i = 0; i < [buttonsArray count]; i++)
{
    UIButton *button = [buttonsArray objectAtIndex:i];

    if (button.tag == 3) { // This is the button you wanted to target!
        [button setHidden:YES];
    }
}

Let's make it clear: you did set target and action of UIButton to controller's IBAction method and get the button as sender argument. 让我们说清楚:您确实将UIButton的targetaction设置为控制器的IBAction方法,并获取了按钮作为sender参数。 Now you show UIAlertView and after it is dismissed, you want to send some message to that button, right? 现在,您显示UIAlertView,并且在将其关闭后,您想要向该按钮发送一些消息,对吗?

Another method is to set delegate property for UIAlertView and respond to – alertView:clickedButtonAtIndex: delegate method. 另一个方法是为UIAlertView设置delegate属性并响应– alertView:clickedButtonAtIndex:委托方法。 Trouble is that sender is lost at that point. 问题是sender在那时丢失了。 You may use objc_setAssociatedObject to associate UIButton with UIAlertView and the retrieve it back when delegate method fires: 您可以使用objc_setAssociatedObject将UIButton与UIAlertView关联,并在委托方法触发时将其取回:

#import <objc/runtime.h>
static char myButtonKey = 0; // to use address as a key (value is irrelevant)

- (IBAction)buttonDidClick:(id)button
{
    UIAlertView *alertView = <setup alert>;
    [alertView setDelegate:self];
    objc_setAssociatedObject(alertView, &myButtonKey, button, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    <show alert>;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIButton *thatButton = objc_getAssociatedObject(alertView, &myButtonKey);
    <use thatButton>;
}

Try to create button in this way and add selector to them : 尝试以这种方式创建按钮并向其添加选择器:

for (int i = 0; i < 5; i++)
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];

    button.tag = i;
    [button addTarget:self
               action:@selector(buttonPressedMethod:)
     forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Show View" forState:UIControlStateNormal];

    // add button to subview here
}

In method, just do whatever, you want to do : 在方法中,您可以做任何您想做的事情:

- (void) buttonPressedMethod : (id) sender {
UIButton *selectedButton = (UIButton *)sender;

  if (selectedButton.tag == 0) {

  }

  else if (selectedButton.tag == 1) {

  }


  else {

  }

}

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

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