【发布时间】:2020-12-20 09:02:20
【问题描述】:
我正在使用 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
【问题讨论】:
-
所以 xAccel 应该看起来像 - x: 33, x: 22 ?或者怎么做?
-
所以您不需要分段控制,而您只需在同一标签中显示加速度计数据和陀螺仪数据?不清楚你需要哪个结果。
-
xAccel 只应在分段控制中单击加速度计时打印加速度计的 x 坐标值,而相同的 xAccel 应仅在分段控制中单击陀螺仪时打印陀螺仪的 x 坐标值。
-
这里的问题出在 startAccelerometerUpdates 中。您需要通过点击获取一次数据,然后停止更新,对吗?
-
我已经编辑了原始帖子并添加了一个 gif 以便更好地理解。只有当我按下标签时,我希望值从加速度计更改为陀螺仪。并非所有时间都可以在 gif 中看到。谢谢
标签: ios swift uistoryboard mobile-application