繁体   English   中英

单击按钮获取数组元素

[英]Get Array element on button click

我有一个可变数组,其中数据动态生成。 为此,我有一个UITextField和一个添加UIButton UITextField仅接受数字数据。

当我点击添加按钮时,数据输入如下。

[1,5,6,2,1,5,3,4,........等..

下一个和上一个有两个按钮。

因此,我想要的是,当我单击上一个按钮时,输入的数据必须以相反的顺序顺序显示,并且如果单击下一个按钮,则必须以正向显示它。

使用NSSortDescriptor

   NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
   NSArray *aArrSortDescriptor = [NSArray arrayWithObject:aSortDescriptor];
   NSArray *aArrSorted = [YourArray sortedArrayUsingDescriptors:aArrSortDescriptor];
   NSLog(@"%@",aArrSorted);

请查看文档 ,有关更多信息, 请参见this

您需要按住索引点才能获得此值。通过单击上一个和下一个按钮来递增和递减索引,

- (IBAction)previousClicked:(id)sender {
    if (index != 0) {
        index--;
        self.inputTextField.text = [self.dataArray objectAtIndex:index];
    }
}

- (IBAction)addCLicked:(id)sender {
    [self.dataArray addObject:[NSString stringWithFormat:@"%@",self.inputTextField.text]];
    index = self.dataArray.count;
     self.inputTextField.text = @"";
}

- (IBAction)nextClicked:(id)sender {
    if (index < self.dataArray.count) {
        self.inputTextField.text = [self.dataArray objectAtIndex:index];
        index++;
    }
}

当您单击上一个按钮时,您需要像

NSSortDescriptor *Lowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
[mutableArrayOfNumbers sortUsingDescriptors:[NSArray arrayWithObject:Lowest]];

不知道您在这里问什么,但我无法评论您的问题。 因此,我将回答我理解的问题。

首先,要明确一点,这就是我的理解。 给定一个具有NSNumber (或为NSString ?)的数组,例如@[@1, @5, @6, @2, @1, @5] ,您想要获取之前输入的数字,依此类推每次点击上一个按钮。 以及点击下一步按钮时的下一个。 我对么?

如果是这样,这就是答案。

@interface SomeViewController ()
{
    NSArray *numbers;
    NSInteger currentIndex;
}

@end

@implementation SomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Init the array and the index with demo values
        numbers = @[@1, @5, @6, @2, @1, @5];
        currentIndex = 3; // that is @2

        NSLog(@"Simulate a tap on the previous button, twice in a row");
        [self tappingPreviousButton]; // 6
        [self tappingPreviousButton]; // 5

        NSLog(@"Simulate a tap on the next button, twice in a row");
        [self tappingNextButton]; // 6
        [self tappingNextButton]; // 2

        // this will print the sequence 6 and 5, then 6 and 2
    }
    return self;
}

- (void)tappingPreviousButton
{
    currentIndex = MAX(currentIndex - 1, 0); // prevent the index to fall below 0
    NSLog(@"%@", numbers[currentIndex]);
}

- (void)tappingNextButton
{
    currentIndex = MIN(currentIndex + 1, [numbers count] - 1); // prevent the index to go above the number of items in your array
    NSLog(@"%@", numbers[currentIndex]);
}

@end

诀窍是让变量跟踪您所在的数组的索引。 然后,您可以删除一个(上一个)或添加一个(下一个)以获得所需的数组值。

希望能有所帮助!

暂无
暂无

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

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