0

我想在每次按下按钮时向用户展示来自 ABC 的不同字母。

所以当它第一次点击应用程序时,用户会看到字母 A,然后他们需要按下按钮,然后他们会看到字母 B,依此类推。

我的挑战是如何在每次单击按钮时替换标题文本。我写了一些代码,两个函数,如果你仔细看看你会发现-(void)displayABC:(id)sender每次都被调用所以每次我得到数组的第一个成员,所以用户第一次看到字母 A 然后按下在按钮上,她/他看到字母 B,它是数组的第一个成员,但是每个相同的字母都出现了,因为每次我们加载 plist 文件,因此我们一直调用数组的第一个成员。

任何想法如何解决它?

-(void)createLoginBioButton
{
    authButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [authButton setBounds:CGRectMake(300,300, 150, 150)];
    [authButton setCenter:CGPointMake(150, 240)];
    [self.view addSubview:authButton];
    [authButton setEnabled:true];
    [authButton setTitle:@"A" forState:UIControlStateNormal];
    [authButton setFont:[UIFont systemFontOfSize:70]];
    [authButton addTarget:self
                   action:@selector(displayABC:) 
         forControlEvents:UIControlEventAllTouchEvents];
 }

-(void)displayABC:(id)sender
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ABC" ofType:@"plist"];
    NSArray *ABCArray = [NSArray arrayWithContentsOfFile:path];
    for (NSString *ABCValues in ABCArray){
        [authButton setTitle:ABCValues forState:UIControlStateNormal];
    }
}
4

2 回答 2

0

为什么不保留对当前字母索引的引用作为实例变量并在每次触摸时增加它呢?

伪代码

@property NSArray *abcs;
@property int currentIndex;

- (void)viewDidLoad {
  [super viewDidLoad];
  self.abcs = //load it from the plist
  [self updateButtonText];
}

- (void)buttonTouched
{
  self.currentIndex++;

  if ( self.currentIndex >= self.abcs.count ) {
    self.currentIndex = 0;
  }
  [self updateButtonText];
}
- (void)updateButtonText
{
  [self.button setTitle:self.abcs[self.currentIndex] forControlState:UIControlStateNormal];
}
于 2013-06-13T18:43:19.840 回答
0

最简单的解决方案是放置一个保持跟踪索引的静态变量

-(void)createLoginBioButton
  {

    authButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [authButton setBounds:CGRectMake(300,300, 150, 150)];
    [authButton setCenter:CGPointMake(150, 240)];
    [self.view addSubview:authButton];
    [authButton setEnabled:true];
    [authButton setTitle:@"A" forState:UIControlStateNormal];
    [authButton setFont:[UIFont systemFontOfSize:70]];
    [authButton addTarget:self action:@selector(displayABC:) forControlEvents:UIControlEventAllTouchEvents];
 }

-(void)displayABC:(id)sender
{

    static int index = 0;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ABC" ofType:@"plist"];
    NSArray *ABCArray = [NSArray arrayWithContentsOfFile:path];
    if(index < [ABCArray count])
        [authButton setTitle:[ABCArray objectAtIndex:index] forState:UIControlStateNormal];
    index++;


}
于 2013-06-14T05:56:51.220 回答