在iOS 7的实例方法中从UILabel获取label.text

时间:2014-02-08 03:49:21

标签: objective-c xcode uilabel

我有一个选择器视图,显示一系列位置(2个组件);下面是2 UILabels(每个组件下2个)。

当用户打开应用程序时,选择器默认为选取器组件中每个数组中的第一个对象,并更改下面的标签以反映该选择。

所以它看起来像这样:

|PickerComponent1|PickerComponent2|

|     Label 1    |     Label 2    |

调用[viewDidLoad]时,它会正确显示标签。标签已更改为相应的名称。

我创建了一个实例方法 - 但是我无法将标签的文本值传递给该方法。

日志显示(null)并且它将返回为空。 关于如何将标签文本正确地传递给方法的任何想法?

* edit:如果我将指定了label1和NSLog行的代码放入viewDidLoad方法,它会相应地打印出标签文本。当我把它放入方法时它没有。

我的.m文件中的viewDidLoad:

- (void)viewDidLoad
{

    //set self as delegate for tripPicker
    _tripPicker.delegate = self;

    //Set size of tripPicker & datePicker
    _tripPicker.transform = CGAffineTransformMakeScale(0.60, 0.60);
    _datePicker.transform = CGAffineTransformMakeScale(0.60, 0.60);

    //Call method to get array of school names (reusable)
    MetaMiles *model = [MetaMiles schoolNameList];
    _schoolArray1 = (NSArray *)model;
    _schoolArray2 = (NSArray *)model;

    //Set date to current date
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    _dateLabel.text = [NSString stringWithFormat:@"Date of trip: %@",[dateFormatter stringFromDate:self.datePicker.date ]];

    //Set selector method for datePicker so on the value change it updates the date
    [self.datePicker addTarget:self action:@selector(updateLabelForDate:) forControlEvents:UIControlEventValueChanged];

    [super viewDidLoad];


    //Set labels to be appropriate schools
    begSchoolLabel.text = [_schoolArray1 objectAtIndex:[_tripPicker selectedRowInComponent:0]];
    endSchoolLabel.text = [_schoolArray2 objectAtIndex:[_tripPicker selectedRowInComponent:1]];


    //Update the Mileage indicator to display miles between currently selected values
    ML54AddMilesViewController *milesObject = [[ML54AddMilesViewController alloc]init];
    NSArray *currentMiles = [milesObject getMileage];
    NSLog(@"Current Miles first run: %@",currentMiles);


}

我的getMileage方法:

- (NSArray *)getMileage {
    //Update the Mileage indicator to display miles between currently selected values
    NSString *begSchool = begSchoolLabel.text;
    NSLog(@"FIRE THIS OFF : %@",begSchool);
    NSString *endSchool = endSchoolLabel.text;
    NSPredicate *milesFilter = [NSPredicate predicateWithFormat:@"beg_school=%@ AND end_school=%@", begSchool, endSchool];
    NSArray *resultMiles = [MetaMiles MR_findAllWithPredicate:milesFilter];
    if (!resultMiles || ![resultMiles count]) {
        NSLog(@"Empty Array");
    } else {
        NSLog(@"Our array is: %@", [resultMiles objectAtIndex:0]);}
    return resultMiles;
}

1 个答案:

答案 0 :(得分:0)

我最终做的不是使用标签来获取文本 - 我只是选择了选择器。标签更新得恰当但由于某种原因我无法在方法之间传递 - 这是我能够做到的另一种方式。