ios - 从 UIAlertView 中的 UITextField 获取文本以设置标签的文本

标签 ios objective-c

我有一个用于创建计时器的标签。我在它下面还有 2 个按钮,最常用的是启动和停止。当我按下开始按钮时,会出现一个警报,警报中有一个文本字段。一切正常,但是当我在警报“开始计时器”中单击我的按钮时,我希望标签具有我在文本字段中设置的数字作为计时器,并倒计时。谁能帮我解决这个问题。我搜索过谷歌,甚至多次尝试使用 label.text = [textField.text intValue] 和所有类似的东西。提前致谢

- (NSString*)getTimeStr : (int) time {
seconds = time % 60;
minutes = time / 60;
return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}

- (IBAction)startTimer{
    // having the user enter a number in seconds
UIAlertView *inputAlert = [[UIAlertView alloc] 
                       initWithTitle:@"Enter The Time:"
               message:@"Enter your time in seconds\n"
                   delegate:self
                   cancelButtonTitle:@"Cancel"
                   otherButtonTitles:@"Start Timer", nil];

UITextField *inputField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
inputField.backgroundColor = [UIColor whiteColor];
[inputAlert addSubview:inputField];
[inputAlert setTag:1];
[inputAlert show];

NSInteger buttonIndex;

if([inputAlert tag] == 1) {
    if(buttonIndex == 1) {
        clicked = TRUE;
        mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 
                                                     target:self 
                                                   selector:@selector(startTimer) 
                                                   userInfo:nil 
                                                    repeats:YES];
    }
    if(buttonIndex == 0) {
        clicked = FALSE;
        [inputAlert dismissWithClickedButtonIndex:0 animated:YES];
    }
} 

//NSString *intFromTextField = [inputField text];
//int time = [intFromTextField intValue];
timeLabel.text = [self getTimeStr:(int)inputField.text];
[timeLabel setFont:[UIFont fontWithName:@"Courier New" size:140]];

最佳答案

好的,所以,这里有两件大事:

首先,您应该设置 alertViewStyle属性为UIAlertViewStylePlainTextInput ,而不是将您自己的文本字段添加到警报 View 。

第二件事是您没有正确地将字符串转换为整数。嗯,你是,但是,出于某种原因它被注释掉了。你不能只是施放它。如果这样做,您将得到对象的内存地址,而不是值。你会想调用integerValue而不是在字符串上。

因此,您将得到类似下面的内容,其中您使用了 UIAlertViewDelegate回调并通过 textFieldAtIndex: 访问文本字段方法:

- (void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger) buttonIndex {
    // Your existing timer code. It's pretty okay as it is.

    NSUInteger enteredInteger = [[alertView textFieldAtIndex:0].text integerValue];
    myLabel.text = [self getTimeStr:enteredInteger];
}

关于ios - 从 UIAlertView 中的 UITextField 获取文本以设置标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992064/

相关文章:

ios - 使用 NSPredicate 的搜索模型

objective-c - iOS 5 和应用商店

ios - 在新的 ViewController 中声明时出现 Serval 问题/错误

ios - jquery mobile,cordova 不能在 iphone 模拟器上工作

ios - 如何在 iOS 中搜索姓名列表?

objective-c - 使用核心图形的背景颜色

iphone - 如何使用带有 Xcode 查找和替换选项的正则表达式删除文件中的所有 NSLog 语句

ios - XCTest.框架/XCTest : no matching architecture in universal wrapper when run the app

ios - 将 touchupinside 添加到以编程方式创建的按钮,并将 NSDate 提交到文本字段

ios - 如何在 iOS 7 下对 UIButton 产生涟漪效果?