How to dinamically change values in labels in a SegmentedControl? Swift 4, iOS2019 Community Moderator ElectionHow to change the name of an iOS app?How do I animate constraint changes?How to change Status Bar text color in iOSHow to call Objective-C code from SwiftHow would I create a UIAlertView in Swift?How do I check if a string contains another string in Swift?How to use background thread in swift?Swift how to sort array of custom objects by property valueAdding a custom UIViewcontroller to subview programmatically but getting an error message “Cannot convert value of type…”How to optimize UITableViewCell, because my UITableView lags

Co-worker team leader wants to inject his friend's awful software into our development. What should I say to our common boss?

Life insurance that covers only simultaneous/dual deaths

How to deal with taxi scam when on vacation?

Meaning of "SEVERA INDEOVI VAS" from 3rd Century slab

The use of "touch" and "touch on" in context

Connecting top and bottom SMD component pads using via

Instead of Universal Basic Income, why not Universal Basic NEEDS?

Ban on all campaign finance?

How to deal with a cynical class?

How could a female member of a species produce eggs unto death?

Why is "das Weib" grammatically neuter?

Russian cases: A few examples, I'm really confused

What is the greatest age difference between a married couple in Tanach?

I need to drive a 7/16" nut but am unsure how to use the socket I bought for my screwdriver

Where is the 1/8 CR apprentice in Volo's Guide to Monsters?

Why did it take so long to abandon sail after steamships were demonstrated?

Why are there 40 737 Max planes in flight when they have been grounded as not airworthy?

Making a sword in the stone, in a medieval world without magic

Is it true that real estate prices mainly go up?

Using "wallow" verb with object

How is the Swiss post e-voting system supposed to work, and how was it wrong?

Is a lawful good "antagonist" effective?

Bash replace string at multiple places in a file from command line

Identifying the interval from A♭ to D♯



How to dinamically change values in labels in a SegmentedControl? Swift 4, iOS



2019 Community Moderator ElectionHow to change the name of an iOS app?How do I animate constraint changes?How to change Status Bar text color in iOSHow to call Objective-C code from SwiftHow would I create a UIAlertView in Swift?How do I check if a string contains another string in Swift?How to use background thread in swift?Swift how to sort array of custom objects by property valueAdding a custom UIViewcontroller to subview programmatically but getting an error message “Cannot convert value of type…”How to optimize UITableViewCell, because my UITableView lags










0















I have some issues with the implementation of a segmented control.
I come to you (the more experienced people) to get some advice about what I should do in order to fix this. Here I go:



For "current" tab, the "Panel's optimal azimuth" and "Panel's optimal tilt angle" should be "tracking the sun" (a code that I will add later), in other words: those 2 fields must update in real time (again, that code I will do it later). The "Panel's current azimuth" and "Panels current tilt angle" basically change according to the phone's position (I use coreMotion and coreLocation to get them).



The problem is this (images added after the explanation):



For the "current" tab, the fields of "panel's optimal azimuth" and "Panel's optimal tilt angle" must change with time. "Panel's current tilt angle" must show from the beginning
the panel's (phone's) tilting and it doesn't do it (only does it when you select another tab).



The "Panel's Optimal Tilt Angle" must have a fixed (but different) value for
the 3, 6 months and "Year" tabs. "Panel's Optimal Azimuth" is the same for the 3, 6 months and "year" tabs (that code I will add it later as well). Nevertheless, I have problems when I select the "Current" tab, here, the "Panel's optimal Azimuth" gets the value "tracking the sun", and
when I choose another tab, that value remains when it should say "180º". This only happens when the phone is still on a surface, as soon I move the phone, the value changes to 180º in this field. The opposite happens when I go from other tabs to the "current" tab (instead of showing "tracking the sun" it shows "180º", again, this value appears when the phone is moving, but if the phone is still, "tracking the sun" is shown).



Basically the only field that's properly working is the "Panel's current Azimuth" in all the 4 tabs in the segmented control.



Please refer to the images to get a better idea.



What I get in the initial view



What I want in the initial view



What I get if the phone is moving (this is correct for the 3, 6 months and year tabs)



What I get if the phone is still, if I chose the "current" tab while the phone was still and then I selected another tab



Same as previos image



So, the question that I have is: What can I do in order to prevent this? I tried to use a switch-case statement inside an @IBAction corresponding to the segmented control, but it is evident that it doesn't work. Here I
share with you the code that I have used for my project:



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"
panelCurrentTilt.text = myDeviceMotion()
case 1:
print("3 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 2:
print("6 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 3:
print("Year tab")
panelCurrentTilt.text = String(myDeviceMotion())

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()





//MARK: - Motion methods
func myDeviceMotion() -> String

var currentTilt:String = "0.0º"
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"

currentTilt = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



return currentTilt



//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

self.panelCurrentAz.text = "(String(format: "%.0f", trueHeading))º"

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º
var panelHeading = 0.0
if GlobalData.latit >= 0.0

self.panelOptimalAz.text = "180º"
panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"



else

self.panelOptimalAz.text = "0º"
panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"










Thanks in advance for your time and your advice.



Greetings.










share|improve this question
























  • A little confusing... You want OptimalAz to display "Tracking the Sun" -- but then you update it to either "180º" or "0º" every time the heading changes? Do you want it to continue to say "Tracking"? Other than that, I don't see any differences in your code when 3 months, 6 months or Year is selected?

    – DonMag
    Mar 7 at 13:19











  • Additionally, you keep re-starting the motion manager... it only needs to be started once (like the location manager). And, with your current code, func myDeviceMotion() will always return "0.0º". I assume that's not what you want?

    – DonMag
    Mar 7 at 13:25











  • Hello DonMag, "Tracking the Sun" is a temporarily substitute for the correct values that I will add later (that code hasn't been done yet). It is 180º if you live in the North Hemisphere (like London) and 0º if you live in the Southern one (i.e. NZ). For now, what I want is that if the tab is on "Current", then it should say "Tracking...", and 180º for the other 3.

    – J_A_F_Casillas
    Mar 7 at 13:35











  • For the 2nd comment, no, i don't want that, but I didn't know what to do in order to give the correct values according to the selected tab. Basically I'd need to use an if-else statement inside the switch-case one and call the function in the if-else statement, which I can not do. That "return 0.0" was an inefficient solution to make that field work.

    – J_A_F_Casillas
    Mar 7 at 13:37















0















I have some issues with the implementation of a segmented control.
I come to you (the more experienced people) to get some advice about what I should do in order to fix this. Here I go:



For "current" tab, the "Panel's optimal azimuth" and "Panel's optimal tilt angle" should be "tracking the sun" (a code that I will add later), in other words: those 2 fields must update in real time (again, that code I will do it later). The "Panel's current azimuth" and "Panels current tilt angle" basically change according to the phone's position (I use coreMotion and coreLocation to get them).



The problem is this (images added after the explanation):



For the "current" tab, the fields of "panel's optimal azimuth" and "Panel's optimal tilt angle" must change with time. "Panel's current tilt angle" must show from the beginning
the panel's (phone's) tilting and it doesn't do it (only does it when you select another tab).



The "Panel's Optimal Tilt Angle" must have a fixed (but different) value for
the 3, 6 months and "Year" tabs. "Panel's Optimal Azimuth" is the same for the 3, 6 months and "year" tabs (that code I will add it later as well). Nevertheless, I have problems when I select the "Current" tab, here, the "Panel's optimal Azimuth" gets the value "tracking the sun", and
when I choose another tab, that value remains when it should say "180º". This only happens when the phone is still on a surface, as soon I move the phone, the value changes to 180º in this field. The opposite happens when I go from other tabs to the "current" tab (instead of showing "tracking the sun" it shows "180º", again, this value appears when the phone is moving, but if the phone is still, "tracking the sun" is shown).



Basically the only field that's properly working is the "Panel's current Azimuth" in all the 4 tabs in the segmented control.



Please refer to the images to get a better idea.



What I get in the initial view



What I want in the initial view



What I get if the phone is moving (this is correct for the 3, 6 months and year tabs)



What I get if the phone is still, if I chose the "current" tab while the phone was still and then I selected another tab



Same as previos image



So, the question that I have is: What can I do in order to prevent this? I tried to use a switch-case statement inside an @IBAction corresponding to the segmented control, but it is evident that it doesn't work. Here I
share with you the code that I have used for my project:



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"
panelCurrentTilt.text = myDeviceMotion()
case 1:
print("3 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 2:
print("6 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 3:
print("Year tab")
panelCurrentTilt.text = String(myDeviceMotion())

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()





//MARK: - Motion methods
func myDeviceMotion() -> String

var currentTilt:String = "0.0º"
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"

currentTilt = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



return currentTilt



//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

self.panelCurrentAz.text = "(String(format: "%.0f", trueHeading))º"

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º
var panelHeading = 0.0
if GlobalData.latit >= 0.0

self.panelOptimalAz.text = "180º"
panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"



else

self.panelOptimalAz.text = "0º"
panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"










Thanks in advance for your time and your advice.



Greetings.










share|improve this question
























  • A little confusing... You want OptimalAz to display "Tracking the Sun" -- but then you update it to either "180º" or "0º" every time the heading changes? Do you want it to continue to say "Tracking"? Other than that, I don't see any differences in your code when 3 months, 6 months or Year is selected?

    – DonMag
    Mar 7 at 13:19











  • Additionally, you keep re-starting the motion manager... it only needs to be started once (like the location manager). And, with your current code, func myDeviceMotion() will always return "0.0º". I assume that's not what you want?

    – DonMag
    Mar 7 at 13:25











  • Hello DonMag, "Tracking the Sun" is a temporarily substitute for the correct values that I will add later (that code hasn't been done yet). It is 180º if you live in the North Hemisphere (like London) and 0º if you live in the Southern one (i.e. NZ). For now, what I want is that if the tab is on "Current", then it should say "Tracking...", and 180º for the other 3.

    – J_A_F_Casillas
    Mar 7 at 13:35











  • For the 2nd comment, no, i don't want that, but I didn't know what to do in order to give the correct values according to the selected tab. Basically I'd need to use an if-else statement inside the switch-case one and call the function in the if-else statement, which I can not do. That "return 0.0" was an inefficient solution to make that field work.

    – J_A_F_Casillas
    Mar 7 at 13:37













0












0








0








I have some issues with the implementation of a segmented control.
I come to you (the more experienced people) to get some advice about what I should do in order to fix this. Here I go:



For "current" tab, the "Panel's optimal azimuth" and "Panel's optimal tilt angle" should be "tracking the sun" (a code that I will add later), in other words: those 2 fields must update in real time (again, that code I will do it later). The "Panel's current azimuth" and "Panels current tilt angle" basically change according to the phone's position (I use coreMotion and coreLocation to get them).



The problem is this (images added after the explanation):



For the "current" tab, the fields of "panel's optimal azimuth" and "Panel's optimal tilt angle" must change with time. "Panel's current tilt angle" must show from the beginning
the panel's (phone's) tilting and it doesn't do it (only does it when you select another tab).



The "Panel's Optimal Tilt Angle" must have a fixed (but different) value for
the 3, 6 months and "Year" tabs. "Panel's Optimal Azimuth" is the same for the 3, 6 months and "year" tabs (that code I will add it later as well). Nevertheless, I have problems when I select the "Current" tab, here, the "Panel's optimal Azimuth" gets the value "tracking the sun", and
when I choose another tab, that value remains when it should say "180º". This only happens when the phone is still on a surface, as soon I move the phone, the value changes to 180º in this field. The opposite happens when I go from other tabs to the "current" tab (instead of showing "tracking the sun" it shows "180º", again, this value appears when the phone is moving, but if the phone is still, "tracking the sun" is shown).



Basically the only field that's properly working is the "Panel's current Azimuth" in all the 4 tabs in the segmented control.



Please refer to the images to get a better idea.



What I get in the initial view



What I want in the initial view



What I get if the phone is moving (this is correct for the 3, 6 months and year tabs)



What I get if the phone is still, if I chose the "current" tab while the phone was still and then I selected another tab



Same as previos image



So, the question that I have is: What can I do in order to prevent this? I tried to use a switch-case statement inside an @IBAction corresponding to the segmented control, but it is evident that it doesn't work. Here I
share with you the code that I have used for my project:



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"
panelCurrentTilt.text = myDeviceMotion()
case 1:
print("3 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 2:
print("6 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 3:
print("Year tab")
panelCurrentTilt.text = String(myDeviceMotion())

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()





//MARK: - Motion methods
func myDeviceMotion() -> String

var currentTilt:String = "0.0º"
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"

currentTilt = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



return currentTilt



//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

self.panelCurrentAz.text = "(String(format: "%.0f", trueHeading))º"

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º
var panelHeading = 0.0
if GlobalData.latit >= 0.0

self.panelOptimalAz.text = "180º"
panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"



else

self.panelOptimalAz.text = "0º"
panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"










Thanks in advance for your time and your advice.



Greetings.










share|improve this question
















I have some issues with the implementation of a segmented control.
I come to you (the more experienced people) to get some advice about what I should do in order to fix this. Here I go:



For "current" tab, the "Panel's optimal azimuth" and "Panel's optimal tilt angle" should be "tracking the sun" (a code that I will add later), in other words: those 2 fields must update in real time (again, that code I will do it later). The "Panel's current azimuth" and "Panels current tilt angle" basically change according to the phone's position (I use coreMotion and coreLocation to get them).



The problem is this (images added after the explanation):



For the "current" tab, the fields of "panel's optimal azimuth" and "Panel's optimal tilt angle" must change with time. "Panel's current tilt angle" must show from the beginning
the panel's (phone's) tilting and it doesn't do it (only does it when you select another tab).



The "Panel's Optimal Tilt Angle" must have a fixed (but different) value for
the 3, 6 months and "Year" tabs. "Panel's Optimal Azimuth" is the same for the 3, 6 months and "year" tabs (that code I will add it later as well). Nevertheless, I have problems when I select the "Current" tab, here, the "Panel's optimal Azimuth" gets the value "tracking the sun", and
when I choose another tab, that value remains when it should say "180º". This only happens when the phone is still on a surface, as soon I move the phone, the value changes to 180º in this field. The opposite happens when I go from other tabs to the "current" tab (instead of showing "tracking the sun" it shows "180º", again, this value appears when the phone is moving, but if the phone is still, "tracking the sun" is shown).



Basically the only field that's properly working is the "Panel's current Azimuth" in all the 4 tabs in the segmented control.



Please refer to the images to get a better idea.



What I get in the initial view



What I want in the initial view



What I get if the phone is moving (this is correct for the 3, 6 months and year tabs)



What I get if the phone is still, if I chose the "current" tab while the phone was still and then I selected another tab



Same as previos image



So, the question that I have is: What can I do in order to prevent this? I tried to use a switch-case statement inside an @IBAction corresponding to the segmented control, but it is evident that it doesn't work. Here I
share with you the code that I have used for my project:



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"
panelCurrentTilt.text = myDeviceMotion()
case 1:
print("3 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 2:
print("6 months Tab")
panelCurrentTilt.text = String(myDeviceMotion())

case 3:
print("Year tab")
panelCurrentTilt.text = String(myDeviceMotion())

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()





//MARK: - Motion methods
func myDeviceMotion() -> String

var currentTilt:String = "0.0º"
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"

currentTilt = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



return currentTilt



//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

self.panelCurrentAz.text = "(String(format: "%.0f", trueHeading))º"

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º
var panelHeading = 0.0
if GlobalData.latit >= 0.0

self.panelOptimalAz.text = "180º"
panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"



else

self.panelOptimalAz.text = "0º"
panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

panelHeading += 0.0
self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"










Thanks in advance for your time and your advice.



Greetings.







ios swift uisegmentedcontrol segmentedcontrol






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 13:26









AtulParmar

1,218522




1,218522










asked Mar 7 at 12:14









J_A_F_CasillasJ_A_F_Casillas

34




34












  • A little confusing... You want OptimalAz to display "Tracking the Sun" -- but then you update it to either "180º" or "0º" every time the heading changes? Do you want it to continue to say "Tracking"? Other than that, I don't see any differences in your code when 3 months, 6 months or Year is selected?

    – DonMag
    Mar 7 at 13:19











  • Additionally, you keep re-starting the motion manager... it only needs to be started once (like the location manager). And, with your current code, func myDeviceMotion() will always return "0.0º". I assume that's not what you want?

    – DonMag
    Mar 7 at 13:25











  • Hello DonMag, "Tracking the Sun" is a temporarily substitute for the correct values that I will add later (that code hasn't been done yet). It is 180º if you live in the North Hemisphere (like London) and 0º if you live in the Southern one (i.e. NZ). For now, what I want is that if the tab is on "Current", then it should say "Tracking...", and 180º for the other 3.

    – J_A_F_Casillas
    Mar 7 at 13:35











  • For the 2nd comment, no, i don't want that, but I didn't know what to do in order to give the correct values according to the selected tab. Basically I'd need to use an if-else statement inside the switch-case one and call the function in the if-else statement, which I can not do. That "return 0.0" was an inefficient solution to make that field work.

    – J_A_F_Casillas
    Mar 7 at 13:37

















  • A little confusing... You want OptimalAz to display "Tracking the Sun" -- but then you update it to either "180º" or "0º" every time the heading changes? Do you want it to continue to say "Tracking"? Other than that, I don't see any differences in your code when 3 months, 6 months or Year is selected?

    – DonMag
    Mar 7 at 13:19











  • Additionally, you keep re-starting the motion manager... it only needs to be started once (like the location manager). And, with your current code, func myDeviceMotion() will always return "0.0º". I assume that's not what you want?

    – DonMag
    Mar 7 at 13:25











  • Hello DonMag, "Tracking the Sun" is a temporarily substitute for the correct values that I will add later (that code hasn't been done yet). It is 180º if you live in the North Hemisphere (like London) and 0º if you live in the Southern one (i.e. NZ). For now, what I want is that if the tab is on "Current", then it should say "Tracking...", and 180º for the other 3.

    – J_A_F_Casillas
    Mar 7 at 13:35











  • For the 2nd comment, no, i don't want that, but I didn't know what to do in order to give the correct values according to the selected tab. Basically I'd need to use an if-else statement inside the switch-case one and call the function in the if-else statement, which I can not do. That "return 0.0" was an inefficient solution to make that field work.

    – J_A_F_Casillas
    Mar 7 at 13:37
















A little confusing... You want OptimalAz to display "Tracking the Sun" -- but then you update it to either "180º" or "0º" every time the heading changes? Do you want it to continue to say "Tracking"? Other than that, I don't see any differences in your code when 3 months, 6 months or Year is selected?

– DonMag
Mar 7 at 13:19





A little confusing... You want OptimalAz to display "Tracking the Sun" -- but then you update it to either "180º" or "0º" every time the heading changes? Do you want it to continue to say "Tracking"? Other than that, I don't see any differences in your code when 3 months, 6 months or Year is selected?

– DonMag
Mar 7 at 13:19













Additionally, you keep re-starting the motion manager... it only needs to be started once (like the location manager). And, with your current code, func myDeviceMotion() will always return "0.0º". I assume that's not what you want?

– DonMag
Mar 7 at 13:25





Additionally, you keep re-starting the motion manager... it only needs to be started once (like the location manager). And, with your current code, func myDeviceMotion() will always return "0.0º". I assume that's not what you want?

– DonMag
Mar 7 at 13:25













Hello DonMag, "Tracking the Sun" is a temporarily substitute for the correct values that I will add later (that code hasn't been done yet). It is 180º if you live in the North Hemisphere (like London) and 0º if you live in the Southern one (i.e. NZ). For now, what I want is that if the tab is on "Current", then it should say "Tracking...", and 180º for the other 3.

– J_A_F_Casillas
Mar 7 at 13:35





Hello DonMag, "Tracking the Sun" is a temporarily substitute for the correct values that I will add later (that code hasn't been done yet). It is 180º if you live in the North Hemisphere (like London) and 0º if you live in the Southern one (i.e. NZ). For now, what I want is that if the tab is on "Current", then it should say "Tracking...", and 180º for the other 3.

– J_A_F_Casillas
Mar 7 at 13:35













For the 2nd comment, no, i don't want that, but I didn't know what to do in order to give the correct values according to the selected tab. Basically I'd need to use an if-else statement inside the switch-case one and call the function in the if-else statement, which I can not do. That "return 0.0" was an inefficient solution to make that field work.

– J_A_F_Casillas
Mar 7 at 13:37





For the 2nd comment, no, i don't want that, but I didn't know what to do in order to give the correct values according to the selected tab. Basically I'd need to use an if-else statement inside the switch-case one and call the function in the if-else statement, which I can not do. That "return 0.0" was an inefficient solution to make that field work.

– J_A_F_Casillas
Mar 7 at 13:37












1 Answer
1






active

oldest

votes


















0














Recapping...



OptimalAz label should say "Tracking the Sun" if the current selected segment is "Current", so add an if () in didUpdateHeading to only update that label when the other segments are selected.



Start the motion manager in viewDidLoad() (along with location manager)... it will continue to run - and continue to update the labels - so no need for a myDeviceMotion() func.



At the end of viewDidLoad(), trigger indexChanged() to initialize the labels (and any other needed tasks / vars) as if the user tapped the "Current" segment.



Give this a try (I think I put enough comments in the code to explain any changes):



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate {

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"

case 1:
print("3 months Tab")
// do something related to 3 months

case 2:
print("6 months Tab")
// do something related to 6 months

case 3:
print("Year tab")
// do something related to Year

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()



// start the motion manager here, since we want it running all the time
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



// call segment changed to update on start (as if user tapped seg 0)
self.indexChanged(segmentedControl)



//MARK: - Motion methods

// no need for this
// func myDeviceMotion() -> String
//
// var currentTilt:String = "0.0º"
//
// return currentTilt
//
//

//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º

var panelHeading = 0.0

// I don't have your GlobalData object, so
// just hard-coding 1.0 here...

// if GlobalData.latit >= 0.0
if 1.0 >= 0.0

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "180º"


panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "0º"


panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"











share|improve this answer























  • Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

    – J_A_F_Casillas
    Mar 7 at 14:09











  • Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

    – J_A_F_Casillas
    Mar 8 at 9:03










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55043542%2fhow-to-dinamically-change-values-in-labels-in-a-segmentedcontrol-swift-4-ios%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Recapping...



OptimalAz label should say "Tracking the Sun" if the current selected segment is "Current", so add an if () in didUpdateHeading to only update that label when the other segments are selected.



Start the motion manager in viewDidLoad() (along with location manager)... it will continue to run - and continue to update the labels - so no need for a myDeviceMotion() func.



At the end of viewDidLoad(), trigger indexChanged() to initialize the labels (and any other needed tasks / vars) as if the user tapped the "Current" segment.



Give this a try (I think I put enough comments in the code to explain any changes):



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate {

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"

case 1:
print("3 months Tab")
// do something related to 3 months

case 2:
print("6 months Tab")
// do something related to 6 months

case 3:
print("Year tab")
// do something related to Year

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()



// start the motion manager here, since we want it running all the time
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



// call segment changed to update on start (as if user tapped seg 0)
self.indexChanged(segmentedControl)



//MARK: - Motion methods

// no need for this
// func myDeviceMotion() -> String
//
// var currentTilt:String = "0.0º"
//
// return currentTilt
//
//

//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º

var panelHeading = 0.0

// I don't have your GlobalData object, so
// just hard-coding 1.0 here...

// if GlobalData.latit >= 0.0
if 1.0 >= 0.0

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "180º"


panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "0º"


panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"











share|improve this answer























  • Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

    – J_A_F_Casillas
    Mar 7 at 14:09











  • Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

    – J_A_F_Casillas
    Mar 8 at 9:03















0














Recapping...



OptimalAz label should say "Tracking the Sun" if the current selected segment is "Current", so add an if () in didUpdateHeading to only update that label when the other segments are selected.



Start the motion manager in viewDidLoad() (along with location manager)... it will continue to run - and continue to update the labels - so no need for a myDeviceMotion() func.



At the end of viewDidLoad(), trigger indexChanged() to initialize the labels (and any other needed tasks / vars) as if the user tapped the "Current" segment.



Give this a try (I think I put enough comments in the code to explain any changes):



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate {

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"

case 1:
print("3 months Tab")
// do something related to 3 months

case 2:
print("6 months Tab")
// do something related to 6 months

case 3:
print("Year tab")
// do something related to Year

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()



// start the motion manager here, since we want it running all the time
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



// call segment changed to update on start (as if user tapped seg 0)
self.indexChanged(segmentedControl)



//MARK: - Motion methods

// no need for this
// func myDeviceMotion() -> String
//
// var currentTilt:String = "0.0º"
//
// return currentTilt
//
//

//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º

var panelHeading = 0.0

// I don't have your GlobalData object, so
// just hard-coding 1.0 here...

// if GlobalData.latit >= 0.0
if 1.0 >= 0.0

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "180º"


panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "0º"


panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"











share|improve this answer























  • Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

    – J_A_F_Casillas
    Mar 7 at 14:09











  • Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

    – J_A_F_Casillas
    Mar 8 at 9:03













0












0








0







Recapping...



OptimalAz label should say "Tracking the Sun" if the current selected segment is "Current", so add an if () in didUpdateHeading to only update that label when the other segments are selected.



Start the motion manager in viewDidLoad() (along with location manager)... it will continue to run - and continue to update the labels - so no need for a myDeviceMotion() func.



At the end of viewDidLoad(), trigger indexChanged() to initialize the labels (and any other needed tasks / vars) as if the user tapped the "Current" segment.



Give this a try (I think I put enough comments in the code to explain any changes):



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate {

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"

case 1:
print("3 months Tab")
// do something related to 3 months

case 2:
print("6 months Tab")
// do something related to 6 months

case 3:
print("Year tab")
// do something related to Year

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()



// start the motion manager here, since we want it running all the time
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



// call segment changed to update on start (as if user tapped seg 0)
self.indexChanged(segmentedControl)



//MARK: - Motion methods

// no need for this
// func myDeviceMotion() -> String
//
// var currentTilt:String = "0.0º"
//
// return currentTilt
//
//

//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º

var panelHeading = 0.0

// I don't have your GlobalData object, so
// just hard-coding 1.0 here...

// if GlobalData.latit >= 0.0
if 1.0 >= 0.0

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "180º"


panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "0º"


panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"











share|improve this answer













Recapping...



OptimalAz label should say "Tracking the Sun" if the current selected segment is "Current", so add an if () in didUpdateHeading to only update that label when the other segments are selected.



Start the motion manager in viewDidLoad() (along with location manager)... it will continue to run - and continue to update the labels - so no need for a myDeviceMotion() func.



At the end of viewDidLoad(), trigger indexChanged() to initialize the labels (and any other needed tasks / vars) as if the user tapped the "Current" segment.



Give this a try (I think I put enough comments in the code to explain any changes):



import UIKit
import CoreMotion
import CoreLocation

class PVOrientationViewController: UIViewController, CLLocationManagerDelegate {

//MARK: - Constants and Variables
let motionManager = CMMotionManager()
let locationManager = CLLocationManager()
var segIndex = 0

//MARK: - Outlets, views, actions
@IBOutlet weak var panelOptimalAz: UILabel!
@IBOutlet weak var panelOptimalTilt: UILabel!
@IBOutlet weak var panelCurrentAz: UILabel!
@IBOutlet weak var panelCurrentTilt: UILabel!

@IBOutlet weak var segmentedControl: UISegmentedControl!

//MARK: - Action of the Segmented Button.
@IBAction func indexChanged(_ sender: Any)

segIndex = segmentedControl.selectedSegmentIndex

switch segIndex

case 0:
print("Current Tab")
panelOptimalAz.text = "Tracking the Sun"

case 1:
print("3 months Tab")
// do something related to 3 months

case 2:
print("6 months Tab")
// do something related to 6 months

case 3:
print("Year tab")
// do something related to Year

default:
panelOptimalAz.text = "No Optimal Azimuth given"
panelCurrentAz.text = "No Current Azimuth given"
panelCurrentTilt.text = "No Current Tilt given"
panelOptimalTilt.text = "No Optimal Tilt given"





//MARK: - viewDidLoad()
override func viewDidLoad()
super.viewDidLoad()

locationManager.delegate = self

// Azimuth
if (CLLocationManager.headingAvailable())

locationManager.headingFilter = 1
locationManager.startUpdatingHeading()



// start the motion manager here, since we want it running all the time
if motionManager.isDeviceMotionAvailable

motionManager.deviceMotionUpdateInterval = 0.1

motionManager.startDeviceMotionUpdates(to: OperationQueue()) (motion, error) -> Void in

if let attitude = motion?.attitude

DispatchQueue.main.async

self.panelCurrentTilt.text = "(String(format:"%.0f", attitude.pitch * 180 / Double.pi))º"







print("Device motion started")

else

print("Device motion unavailable")



// call segment changed to update on start (as if user tapped seg 0)
self.indexChanged(segmentedControl)



//MARK: - Motion methods

// no need for this
// func myDeviceMotion() -> String
//
// var currentTilt:String = "0.0º"
//
// return currentTilt
//
//

//MARK: - True heading and panel's heading
func locationManager(_ manager: CLLocationManager, didUpdateHeading heading: CLHeading)

let trueHeading = heading.trueHeading

//If latitude >= 0, then panel's azimuth = 180º, else, it is 0º

var panelHeading = 0.0

// I don't have your GlobalData object, so
// just hard-coding 1.0 here...

// if GlobalData.latit >= 0.0
if 1.0 >= 0.0

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "180º"


panelHeading = trueHeading - 180.0

if panelHeading < 0

panelHeading += 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"

else

// only update Optimal Az label if "Current" seg is NOT selected
if self.segmentedControl.selectedSegmentIndex != 0
self.panelOptimalAz.text = "0º"


panelHeading = trueHeading + 180.0

if panelHeading > 359.0

panelHeading -= 360.0



self.panelCurrentAz.text = "(String(format: "%.0f", panelHeading))º"












share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 7 at 14:02









DonMagDonMag

17.3k21130




17.3k21130












  • Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

    – J_A_F_Casillas
    Mar 7 at 14:09











  • Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

    – J_A_F_Casillas
    Mar 8 at 9:03

















  • Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

    – J_A_F_Casillas
    Mar 7 at 14:09











  • Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

    – J_A_F_Casillas
    Mar 8 at 9:03
















Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

– J_A_F_Casillas
Mar 7 at 14:09





Thank you DonMag. I will give it a try when I reach my computer. But it seems it may work. I’ll let you know how it goes. Greets.

– J_A_F_Casillas
Mar 7 at 14:09













Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

– J_A_F_Casillas
Mar 8 at 9:03





Thanks DonMag, that helped with what it is needed. The labels of a previous tab still appear if I switch to another tab while the phone is still, but that's a minor bug that doesn't represent any threat since the phone hardly will be 100% still for the purposes of this app. Thanks a lot for your help.

– J_A_F_Casillas
Mar 8 at 9:03



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55043542%2fhow-to-dinamically-change-values-in-labels-in-a-segmentedcontrol-swift-4-ios%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme