ios - 对不同的函数值使用相同的 swift UIlabels
问题描述
我正在使用 swift 编写一个 iOS 应用程序,其中我有 3 个 UILabel,它们会将不同传感器数据的数据显示到相同的相应标签中。
这是我正在使用的 3 个标签。
@IBOutlet weak var xAccel: UILabel!
@IBOutlet weak var yAccel: UILabel!
@IBOutlet weak var zAccel: UILabel!
我正在使用 UIsegmentedControl 更改数据的显示,如下所示。
@IBAction func AccelDidChange(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
myAccelerometer()
break
case 1:
myGyroscope()
break
default:
myAccelerometer()
}
上面用到的2个功能如下
func myAccelerometer() {
// sets the time of each update
motion.accelerometerUpdateInterval = 0.1
//accessing the data from the accelerometer
motion.startAccelerometerUpdates(to: OperationQueue.current!) { (data, error) in
// can print the data on the console for testing purpose
//print(data as Any)
if let trueData = data {
self.view.reloadInputViews()
//setting different coordiantes to respective variables
let x = trueData.acceleration.x
let y = trueData.acceleration.y
let z = trueData.acceleration.z
//setting the variable values to label on UI
self.SensorName.text = "Accelerometer Data"
self.xAccel.text = "x : \(x)"
self.yAccel.text = "y : \(y)"
self.zAccel.text = "z : \(z)"
}
}
}
func myGyroscope() {
motion.gyroUpdateInterval = 0.1
motion.startGyroUpdates(to: OperationQueue.current!) { (data, error) in
if let trueData = data {
self.view.reloadInputViews()
//setting different coordiantes to respective variables
let x = trueData.rotationRate.x
let y = trueData.rotationRate.y
let z = trueData.rotationRate.z
//setting the variable values to label on UI
self.SensorName.text = "Gyroscope Data"
self.xAccel.text = "x: \(x)"
self.yAccel.text = "y: \(y)"
self.zAccel.text = "z: \(z)"
}
}
}
** 问题是它会同时在 UILabel 上同时显示加速度计和陀螺仪数据,而不是在点击时仅显示特定传感器的数据。我尝试使用 break 选项,但仍然无法正常工作。如果有人能指出可能的解决方案,那就太好了。谢谢 **
EIDT - 这是屏幕上的输出,您可以在其中看到不同传感器之间的值波动。我一次只需要 1 个传感器的读数。 https://imgur.com/a/21xW4au
解决方案
@IBAction func AccelDidChange(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
motion.stopGyroUpdates()
myAccelerometer()
break
case 1:
motion.stopDeviceMotionUpdates()
myGyroscope()
break
default:
myAccelerometer()
}
}
您需要在切换之前停止不需要的资源。请试试这个
推荐阅读
- ruby-on-rails - Rails 控制台停止输出任何文本
- docker - 强制 docker 客户端 (CLI) 使用 HTTP 而不是 HTTPS
- firebase - 无法安装 Firebase 消息包
- javascript - 没有脚本标签检测机器人流量
- reactjs - 如何在不刷新的情况下上传新图像后更新旧头像图像
- javascript - Reducer 突然在商店中添加商品
- python - UnicodeEncodeError:“ascii”编解码器无法在位置 37 编码字符“\u201c”:序数不在范围内(128)
- firebase - 安装 Firebase CLI 时出现意外的 Json
- c# - 更改数据库中的数据时列表框不刷新
- python - 运行 conda clean 但文件存在时出现 Filenotfound 错误