我正在尝试创建将数字输入标签的键盘界面。您可以更轻松地按键盘输入4位数字的输入键,就像打开锁定的iOS设备一样。
我有四个标签,会显示输入的数字。我有12个按钮,其中包含数字(加上取消和删除按钮)。每个按钮都有一个分配给它的标签。 单击按钮时,我希望将该标记作为文本输入到下一个空标签。
我需要做的是引用setPin函数中的下一个空标签。我是以错误的方式解决这个问题还是只是因为我错过了一点?我的代码的精简版本如下。
- (void)viewDidLoad
{
[super viewDidLoad];
[[self view] setBackgroundColor:[UIColor whiteColor]];
[self setCurrField:1];
// BUILD A VIEW TO CONTAIN THE LOGIN PANEL
UIView *pinView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 400, 500)];
pinView.backgroundColor = [UIColor lightGrayColor];
// CREATE BUTTONS
int nPos = 1;
int leftPos;
int topPos = 134;
while (nPos <= 12)
{
leftPos = (nPos%3 == 1) ? 19 : leftPos + 113 + 12;
topPos = (nPos%3 == 1) ? topPos + 61 + 10 : topPos;
// BUILD THE BUTTONS AND ADD TO THE PAGE
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTag:nPos];
[btn addTarget:self action:@selector(setPin:) forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:CGRectMake(leftPos, topPos, 113, 61)];
[btn setBackgroundColor: [UIColor darkGrayColor]];
NSString *btnLabel;
if(nPos <= 9)
{
btnLabel = [NSString stringWithFormat:@"%i", nPos];
}
else
{
switch (nPos) {
case 10:
btnLabel = @"Cancel";
break;
case 11:
btnLabel = @"0";
break;
case 12:
btnLabel = @"Delete";
break;
default:
break;
}
}
[btn setTitle: btnLabel forState:UIControlStateNormal];
[pinView addSubview:btn];
nPos++;
}
// CREATE THE TEXTBOXES
UILabel *char1Label = [[UILabel alloc] initWithFrame:CGRectMake(19, 65, 83, 91)];
UILabel *char2Label = [[UILabel alloc] initWithFrame:CGRectMake(113, 65, 83, 91)];
UILabel *char3Label = [[UILabel alloc] initWithFrame:CGRectMake(207, 65, 83, 91)];
UILabel *char4Label = [[UILabel alloc] initWithFrame:CGRectMake(301, 65, 83, 91)];
[pinView addSubview:char1Label];
[pinView addSubview:char2Label];
[pinView addSubview:char3Label];
[pinView addSubview:char4Label];
[[self view] addSubview:pinView];
}
-(void)setPin:(UIButton *)sender
{
if(sender.tag <= 9 || sender.tag == 11)
{
[--charLabel[self currField]Label-- setText:[sender tag]];
[self currField++];
}
elseif(sender.tag == 12)
{
[self currField--];
[--charLabel[self currField]Label-- setText:@""];
}
}
答案 0 :(得分:1)
您需要保留对textLabels的引用,可能作为您所在类的属性。
@property (nonatomic) NSArray* textLabels; // Choose a more descriptive name than this
...
self.textLabels = @[ char1Label, char2Label, char3Label, char4Label ];
...
- (UILabel*) nextEmptyLabel {
for (UILabel* label in self.TextLabels)
{
NSString* trimmedText = [label.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([trimmedText length] == 0) {
return label;
}
}
return nil; // No non empty label found
}
答案 1 :(得分:0)
执行此操作的一种方法是将每个标签放入NSMutableArray(以及视图中)。然后在setPin
中获取每个标签:
UILabel *label = [labelArray objectAtIndex:currField];
[label setText:[NSString stringWithFormat:@"%i", sender.tag]];
currField++;