簡體   English   中英

從一個視圖控制器獲取數據到另一個

[英]getting data from one view controller to another

我正在獲取我的藍牙設備(batteryLevel)的電池電量,這是一個視圖中的浮動。 我想將它傳遞給另一個視圖以在文本字段中顯示它。

代碼在視圖中

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:    
    (CBCharacteristic *)characteristic error:(NSError *)error
    {[self.testPeripheral readValueForCharacteristic:mycharacteristic];

    char batlevel;
    [characteristic.value getBytes:&batlevel length:1];
    self.batteryLevel = (float)batlevel;

    NSLog(@"level;%f",batteryLevel);}

這給了我一個像80.00000的值

我想把它放到另一個視圖中顯示。

我已經在我已經放置的view2.h文件中嘗試過了

view1 *t

接着

- (void) batteryIndicatorTimer:(NSTimer *)timer {
    TIBLEUIBatteryBar.progress = t.batteryLevel / 100;
    [t readBattery:[t testPeripheral]];               // Read battery value of keyfob again
    NSLog(@"t.batterylevel:%f",t.batteryLevel);
}

但我沒有得到t.batteryLevel的值

我做錯了什么,怎么能這樣做?

使用委托或在presentationViewControllers / destinationViewControllers中分配屬性有很多方法可以實現這一點,但由於我不知道你的應用程序流程,我會給你一種方法,可以使用你所擁有的任何設置。 只需在viewController中更新batteryLevel即peripheralDelegate,然后將值保存到NSUserDefaults:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:
 (CBCharacteristic *)characteristic error:(NSError *)error
 {
   //Grab your battery value and store in float
   //Then just save to defaults so you can access wherever.. Keep overwriting this value each time you update

   [[NSUserDefaults standardUserDefaults]setFloat:batteryVal forKey:@"battery_level"];

 }

然后在你的另一個viewController里面只是在viewWillAppear里面分配值。

-(void)viewWillAppear:(BOOL)animated
{
    float batteryLevel = [[NSUserDefaults standardUserDefaults]floatForKey:@"battery_level"];
    self.yourTextField.text = [NSString stringWithFormat:@"%f",batteryLevel];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM