我想向用户呈现每次按下来自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];
}
}
答案 0 :(得分:0)
为什么不将当前字母索引的引用保留为实例变量,并在每次触摸时递增?
Psuedo代码
@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];
}
答案 1 :(得分: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++;
}