【问题标题】:Swift 3 Xcode: How to display battery levels as an integer?Swift 3 Xcode:如何将电池电量显示为整数?
【发布时间】:2017-04-05 22:39:09
【问题描述】:

我正在制作一个使用 Swift 读取电池百分比的应用! 现在我的输出是这样的: 61.0% 或 24.0% 或 89.0% 我要解决的是摆脱 .0 所以它是一个 Int。 到目前为止,这是我的代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var infoLabel: UILabel!

var batteryLevel: Float {
    return UIDevice.current.batteryLevel
}

var timer = Timer()

func scheduledTimerWithTimeInterval(){
    timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.someFunction), userInfo: nil, repeats: true)
}

func someFunction() {
    self.infoLabel.text = "\(batteryLevel * 100)%"
}

override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.isBatteryMonitoringEnabled = true
    someFunction()
    scheduledTimerWithTimeInterval()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

我尝试过这样的事情:

var realBatteryLevel = Int(batteryLevel)

但是,我得到了这个error

我尝试了其他方法,但没有任何运气。请,任何解决方案都会很棒!提前致谢!

编辑

我正在考虑将浮点数 batteryLevel 转换为字符串,然后将“.0”替换为“”,我在某处看到过,但是我不确定如何操作!

【问题讨论】:

  • someFunction中进行整数转换或将realBatteryLevel声明为计算变量
  • @Paulw11 不幸的是,无论出于何种原因,这两种方法都不会导致错误,但是它们都使我的输出为 0%

标签: ios swift xcode swift3 string-formatting


【解决方案1】:

试试这个:

func someFunction() {
    self.infoLabel.text = String(format: "%.0f%%", batteryLevel * 100)
}

为了将来参考,所有字符串格式说明符都是listed here

【讨论】:

  • 感谢这工作完美。正是我想要的!
【解决方案2】:

你只需要在你的函数中转换它:

func someFunction() {
self.infoLabel.text = "\(Int(batteryLevel * 100))%" }

【讨论】:

  • batteryLevel 是一个标准化值(即在0.01.0 之间)。因此,Int(batteryLevel) 表达式大部分时间将是
  • 正如@PauloMattos 所说,我在之前的评论中说过,这只会让我的输出每次都等于 0%。感谢您的尝试
  • 我已经编辑了我的答案,试试Int(batteryLevel * 100)
  • @AshXVI @MattPidd 好多了!在这里不要挑剔,但仍然会丢失小数精度,因为没有执行 四舍五入(即,给定的 Int 初始化程序简单地丢弃了小数位)。基于String(format:) 的解决方案,真正由您提供,没有这个问题;-)
【解决方案3】:

或者,您可以为 batteryLevel 创建一个 Int 计算属性:

var batteryLevel: Int {
  return Int(round(UIDevice.current.batteryLevel * 100))
}

请注意,您可能无法获取电池电量。您应该对此进行测试并显示不同的字符串:

if UIDevice.current.batteryState == .unknown {
  self.batteryLevelLabel.text = "n/a"
} else {
  self.batteryLevelLabel.text = "\(self.batteryLevel)%"
}

另请注意,您应该订阅.UIDeviceBatteryLevelDidChange 通知,而不是运行计时器来获取电池电量。处理所有这些的视图控制器的“肉”可能如下所示:

import UIKit

class ViewController: UIViewController {

  @IBOutlet weak var batteryLevelLabel: UILabel!

  ///Holds the notification handler for battery notifications.
  var batteryNotificationHandler: Any?

  ///A computed property that returns the battery level as an int, using rounding.
  var batteryLevel: Int {
    return Int(round(UIDevice.current.batteryLevel * 100))
  }

  ///A function to display the current battery level to a label, 
  ////or the string "n/a" if the battery level can't be determined.
  func showBatteryLevel() {
    if UIDevice.current.batteryState == .unknown {
      self.batteryLevelLabel.text = "n/a"

    } else {
      self.batteryLevelLabel.text = "\(self.batteryLevel)%"
    }
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    ///If we have a battery level observer, remove it since we're about to disappear
    if let observer = batteryNotificationHandler {
      NotificationCenter.default.removeObserver(observer: observer)
    }
  }
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    showBatteryLevel() //display the battery level once as soon as we appear

    //Create a notifiation handler for .UIDeviceBatteryLevelDidChange 
    //notifications that calls showBatteryLevel()
    batteryNotificationHandler =
      NotificationCenter.default.addObserver(forName: .UIDeviceBatteryLevelDidChange,
                                             object: nil,
                                             queue: nil, using: {
                                              (Notification) in
                                              self.showBatteryLevel()
    })
  }

    override func viewDidLoad() {
      super.viewDidLoad()
      //Tell UIDevice that we want battery level notifications
      UIDevice.current.isBatteryMonitoringEnabled = true
  }
}

【讨论】:

  • 正如有人在现已删除的评论中指出的那样,为.UIDeviceBatteryLevelDidChange 通知.UIDeviceBatteryStateDidChange 通知添加观察者确实会更好,所以你可以知道您何时会收到电池电量通知,并且您无需在每次尝试读取电池状态之前检查 UIDevice.current.batteryState。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多