问题描述
我正在使用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- 这是屏幕上的输出,您可以在其中看到不同传感器之间的值波动。我只想一次从一个传感器读取数据。 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()
}
}
在切换之前,您需要停止不需要的资源。请尝试这个