XCode: NSPopUpButton - Set items and get selected item

At first some images how a NSPopUpButton looks like in user interface. There are two types of NSPopUpButton:

Type Pop Up:
Type Pop Up closed Type Pop Up launched

Type Pull Down:
Type Pull Down closed Type Pull Down launched

To fill one or more objects of NSPopUpButton progammatically with items you can use a method like this. As a precaution we remove at first all items, then we fill our PopUp-Button with items and finally we set for every item a tag. So we can identify every item by NSInteger later

- (void) fillPopUpBtnWithItems: (NSPopUpButton *) popupBtn{
    [popupBtn removeAllItems];

    NSString *firstItem = @"Pixel";
    [popupBtn addItemWithTitle:firstItem];
    NSString *secondItem = @"Percent";
    [popupBtn addItemWithTitle:secondItem];

    [[popupBtn itemAtIndex:0]setTag:0];
    [[popupBtn itemAtIndex:1]setTag:1];
}

If you have a lot of items and like to manage them in an array you can use addItemsWithTitles: method

NSArray *array = [[NSArray alloc]initWithObjects:@"Pixel", @"Percent", nil];
[popupBtn addItemsWithTitles:array];

To get the selected item you call:

[popupBtn selectedItem];

And to get the tag for selected item for further actions you simply call the item tag and evaluate it with a switch case expression:

NSInteger tagPopUp = [[popupBtn selectedItem]tag];
switch (tagPopUp) {
case 1:
    //do something, if first item is selected
    break;
case 2:
    //do something, if second item is selected
    break;
default:
    break;
}

Werbung



comments powered by Disqus

Copyright Dunkel & Iwer GbR | Datenschutzerklärung | Impressum