How to loop a Slider value for height? - ios

I successfully created a slider for user height in storyboard and the corresponding code to assign a value in the slider to each level of height but as you can see below, I had to manually copy & paste each new height variable to get it to work. I was curious how an expert would simplify this code? thanks!
*note - I removed the code for height 5'2 to 6'4 to not take up so much space.
'''
#IBOutlet weak var yourHeightEquals: UILabel!
#IBOutlet weak var heightSliderOutlet: UISlider!
#IBAction func heightSliderAction(_ sender: UISlider) {
heightSliderOutlet.value = roundf(heightSliderOutlet.value)
let yourHeightText: String = "Your Height: "
if heightSliderOutlet.value == 0 {
let yourHeightString = "Choose Your Height"
yourHeightEquals.text = yourHeightString
}
else if heightSliderOutlet.value == 1 {
let yourHeightString = "<5'0"
yourHeightEquals.text = yourHeightText + yourHeightString
}
else if heightSliderOutlet.value == 2 {
let yourHeightString = "5'0"
yourHeightEquals.text = yourHeightText + yourHeightString
}
else if heightSliderOutlet.value == 3 {
let yourHeightString = "5'1"
yourHeightEquals.text = yourHeightText + yourHeightString
}
.......
else if heightSliderOutlet.value == 19 {
let yourHeightString = "6'5"
yourHeightEquals.text = yourHeightText + yourHeightString
}
else if heightSliderOutlet.value == 20 {
let yourHeightString = ">6'5"
yourHeightEquals.text = yourHeightText + yourHeightString
}
}
'''

You can use a switch statement like this.
#IBOutlet weak var heightSliderOutlet: UISlider!
#IBOutlet weak var yourHeightEquals: UILabel!
#IBAction func heightSliderAction(_ sender: UISlider) {
let value = roundf(heightSliderOutlet.value)
switch value {
case 0:
yourHeightEquals.text = "Choose Your Height"
case 1:
yourHeightEquals.text = "Your Height : <5'0"
case 2...19:
let height = 5.0 + ((value - 2) * 0.1)
yourHeightEquals.text = "Your Height : \(height)"
default:
yourHeightEquals.text = "Your Height: >6'5"
}
}

Update - the switch code above only worked for a metric system - I had to modify it a bit for feet & inches, still much cleaner than my original code!
#IBOutlet weak var yourHeightEquals: UILabel!
#IBOutlet weak var heightSliderOutlet: UISlider!
#IBAction func heightSliderAction(_ sender: UISlider) {
let value = roundf(heightSliderOutlet.value)
switch value {
case 0:
yourHeightEquals.text = "Choose Your Height"
case 1:
yourHeightEquals.text = "Your Height: <5'0"
case 2...11:
let height = 5.0 + ((value - 2) * 0.1)
let heightstring = String(height)
let heightfoot = heightstring.dropLast(2)
let heightinch = heightstring.dropFirst(2)
let heightfootinch = heightfoot + "'" + heightinch
yourHeightEquals.text = "Your Height: \(heightfootinch)"
case 12:
yourHeightEquals.text = "Your Height: 5'10"
case 13:
yourHeightEquals.text = "Your Height: 5'11"
case 14...19:
let height = 6.0 + ((value - 14) * 0.1)
let heightstring = String(height)
let heightfoot = heightstring.dropLast(2)
let heightinch = heightstring.dropFirst(2)
let heightfootinch = heightfoot + "'" + heightinch
yourHeightEquals.text = "Your Height: \(heightfootinch)"
default:
yourHeightEquals.text = "Your Height: >6'5"
}
}

Related

Individual Labels update value when swiped

Ive got my swipe functionality working now on individual labels due to some great help! Now I just need each of those labels to update individually when swiped, so each label has its own seperate counter and doesnt effect the other ones.
heres my code:
import UIKit
class ViewController: UIViewController {
var counter = 0
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
var counters: [UILabel: Int] = [:]
override func viewDidLoad() {
super.viewDidLoad()
for label: UILabel in [label1, label2, label3] {
counters[label] = 0
for direction: UISwipeGestureRecognizerDirection in [.up, .down, .left, .right] {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(didSwipe(_:)))
swipeGesture.direction = direction
label.addGestureRecognizer(swipeGesture)
label.isUserInteractionEnabled = true
label.isMultipleTouchEnabled = true
}
}
}
#objc func didSwipe(_ gestureRecognizer: UISwipeGestureRecognizer) {
guard let label = gestureRecognizer.view as? UILabel else { return }
debugPrint("\(gestureRecognizer.direction)")
switch gestureRecognizer.direction {
case .up:
counters[label] = counters[label]! + 5
print(counters)
case .down:
counters[label] = 0
print(counters)
case .left:
counters[label] = counters[label]! - 1
print(counters)
case .right:
counters[label] = counters[label]! + 1
print(counters)
default:
label.text = "0"
}
}
}
You need to call
label.text = "\(counters[label]!)"
At the end of your switch statement. This should work.
I see how, set the label of the text at the end of the gesture.
label.text = “(counters[label]!)”
For example,
#objc func didSwipe(_ gestureRecognizer: UISwipeGestureRecognizer) {
guard let label = gestureRecognizer.view as? UILabel else { return }
debugPrint("\(gestureRecognizer.direction)")
switch gestureRecognizer.direction {
case .up:
counters[label] = counters[label]! + 5
print(counters)
case .down:
counters[label] = 0
print(counters)
case .left:
counters[label] = counters[label]! - 1
print(counters)
case .right:
counters[label] = counters[label]! + 1
print(counters)
default:
counters[label] = 0
}
label.text = “\(counters[label]!)”
}

Smiley Rating Bar swift

If we had to do this Smiley Rating Bar on iOS...how we can do?
In the link-example, use a gif, but let's avoid this
If I had to do it ... I would use 5 images of faces for the background with their respective descriptions.
For the face that moves in its position X would use UIPanGestureRecognizer:
class ViewController: UIViewController , UIGestureRecognizerDelegate , UITextFieldDelegate{
#IBOutlet weak var image1: UIImageView!
var panGesture = UIPanGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView(_:)))
image1.isUserInteractionEnabled = true
image1.addGestureRecognizer(panGesture)
}
func draggedView(_ sender:UIPanGestureRecognizer){
self.view.bringSubview(toFront: image1)
let translation = sender.translation(in: self.view)
image1.center = CGPoint(x: image1.center.x + translation.x, y: image1.center.y)
sender.setTranslation(CGPoint.zero, in: self.view)
}
}
The question I have is how do I move the image1 to detect what is going on "above" the images below. Like this:
So...any help I will appreciate
I have done the same thing, Please use
https://github.com/gali8/G8SliderStep/tree/master/G8SliderStep Library .Please replace the Draw labels and Draw Images method with following in G8SliderStep.swift File.
#objc internal func drawLabels() {
guard let ti = tickTitles else {
return
}
if _stepTickLabels == nil {
_stepTickLabels = []
}
if let sl = _stepTickLabels {
for l in sl {
l.removeFromSuperview()
}
_stepTickLabels?.removeAll()
for index in 0..<ti.count {
let title = ti[index]
let lbl = UILabel()
lbl.font = unselectedFont
lbl.text = title
lbl.textAlignment = .center
lbl.sizeToFit()
var offset: CGFloat = 0
if index+1 < (steps%2 == 0 ? steps/2+1 : steps/2) {
offset = trackLeftOffset/2
}
else if index+1 > (steps%2 == 0 ? steps/2+1 : steps/2) {
offset = -(trackRightOffset/2)
}
if index == 0 {
offset = trackLeftOffset
}
if index == steps {
offset = -trackRightOffset
}
let x = offset + CGFloat(Double(index) * stepWidth) - (lbl.frame.size.width / 2)
var rect = lbl.frame
rect.origin.x = x
rect.origin.y = bounds.midY - (bounds.size.height / 2) - rect.size.height + 80
lbl.frame = rect
self.addSubview(lbl)
_stepTickLabels?.append(lbl)
}
}
}
#objc internal func drawImages() {
guard let ti = tickImages else {
return
}
if _stepTickImages == nil {
_stepTickImages = []
}
if let sl = _stepTickImages {
for l in sl {
l.removeFromSuperview()
}
_stepTickImages?.removeAll()
for index in 0..<ti.count {
let img = ti[index]
let imv = UIImageView(image: img)
imv.contentMode = .scaleAspectFit
imv.sizeToFit()
var offset: CGFloat = 0
if index+1 < (steps%2 == 0 ? steps/2+1 : steps/2) {
offset = trackLeftOffset/2
}
else if index+1 > (steps%2 == 0 ? steps/2+1 : steps/2) {
offset = -(trackLeftOffset/2)
}
if index == 0 {
offset = trackLeftOffset
}
if index == steps {
offset = -trackRightOffset
}
let x = offset + CGFloat(Double(index) * stepWidth) - (imv.frame.size.width / 2)
var rect = imv.frame
rect.origin.x = x
rect.origin.y = bounds.midY - (bounds.size.height / 2)
imv.frame = rect
self.insertSubview(imv, at: 2) //index 2 => draw images below the thumb/above the line
_stepTickImages?.append(imv)
}
}
}
Please get selected and unselected emoticons image from your personal resource, and pass those image in array as done in given example.In your view controller in viewDidLoad please write this code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
sliderStepBar.stepImages = [UIImage(named:"terrible")!, UIImage(named:"bad")!, UIImage(named:"okay")!, UIImage(named:"good")!,UIImage(named:"great")!, ]
sliderStepBar.tickTitles = ["Terrible", "Bad", "Okay", "Good", "Great"]
sliderStepBar.tickImages = [#imageLiteral(resourceName: "unselectterrible"), #imageLiteral(resourceName: "unselectbad"), #imageLiteral(resourceName: "unselectokay"),#imageLiteral(resourceName: "unselectgood"),#imageLiteral(resourceName: "unselectgreat")]
sliderStepBar.minimumValue = 4
sliderStepBar.maximumValue = Float(sliderStepBar.stepImages!.count) + sliderStepBar.minimumValue - 1.0
sliderStepBar.stepTickColor = UIColor.clear
sliderStepBar.stepTickWidth = 40
sliderStepBar.stepTickHeight = 40
sliderStepBar.trackHeight = 5
sliderStepBar.value = 5
}
Enjoy the Smiley Rating.
Happy Coding.
I have created the same, Check the below image
Overview
Easy customization(Font, Colors, Images, Ticks, Height, Width, Rounded)
#IBInspectable
Tappable
Draggable
Swift 5.0 above
Xcode 11 above
Orientation support
Manual drag & drop the class
Find the GIT URL for code
SmileyRating

One button with different actions each touch in iOS

I want to change the text (or the background or the animation or what ever) in each click, what is the best way to do it?
#IBOutlet weak var text: UILabel!
#IBOutlet var background: UIView!
#IBOutlet weak var button: UIButton!
#IBAction func play(_ sender: UIButton) {
UIView.animate(withDuration: 1.5) {
self.button.frame.origin.y = 30
self.button.frame.size.height = 200
self.button.frame.size.width = 130
self.button.backgroundColor = .yellow
self.text.textColor = .white
self.text.frame.origin.y += 110
self.background.backgroundColor = .black
self.text.text = "Thanks for grabiN."
// ..text = "Now click it until it's gone!"
// ..text = "ComeOn you can do iT"
// ..text = "Lest time"
}
}
create massive and one count param
var count = 0
var texts = ["Thanks for grabiN.", "ComeOn you can do iT"]
UIView.animate(withDuration: 1.5) {
self.button.frame.origin.y = 30
self.button.frame.size.height = 200
self.button.frame.size.width = 130
self.button.backgroundColor = .yellow
self.text.textColor = .white
self.text.frame.origin.y += 110
self.background.backgroundColor = .black
let index = self.count % self.texts.count
self.text.text = self.texts[index]
self.count+=1
}

How hide a button (from a for loop)?

I've created multiple buttons (12!) in a for loop.
And now I would hide one of these Buttons.
But I dont know how ;)
I used also button.tag, to get the label from every button I touch to fill the text in another label.
BTW: I used this for a PinCode Check and I want to hide the OK_Button until the PinCode is right.
var pinCode = [Int]()
var pinCodeCounter = 0
func pinCodeLabel() {
pinCodeCounter += 1
if pinCodeCounter == 1 {
pinLabel.text = "*"
}
if pinCodeCounter == 2 {
pinLabel.text = "**"
}
if pinCodeCounter == 3 {
pinLabel.text = "***"
}
if pinCodeCounter == 4 {
pinLabel.text = "****"
}
if pinCodeCounter == 0 {
pinLabel.text = ""
}
}
#IBOutlet weak var pinLabel: UILabel!
#IBOutlet weak var pinCodeCheck: UILabel!
#IBOutlet weak var continueToTimeControlView: UIButton!
#IBAction func pinCodeCorrect() {
if pinCode == [8, 1, 1, 8] {
pinCodeCheck.text = "PIN-Code Richtig"
pinCodeCheck.textColor = UIColor.black
continueToTimeControlView.isHidden = false
} else {
pinCodeCheck.text = "PIN-Code Falsch"
pinCodeCheck.textColor = UIColor.red
}
}
let btn_create = UIButton(type: .system)
#IBOutlet weak var attendanceView: UIView!
func btnAction(sender: UIButton!) {
switch (sender.tag) {
case 0:
pinCode.append(1)
print("1")
case 1:
pinCode.append(2)
print("2")
case 2:
pinCode.append(3)
print("3")
case 3:
pinCode.append(4)
print("4")
case 4:
pinCode.append(5)
print("5")
case 5:
pinCode.append(6)
print("6")
case 6:
pinCode.append(7)
print("7")
case 7:
pinCode.append(8)
print("8")
case 8:
pinCode.append(9)
print("9")
case 9:
pinCode.removeAll()
print("<-")
case 10:
pinCode.append(0)
print("0")
case 11:
pinCodeCorrect()
print(pinCode)
print("OK")
default:
print("")
}
pinCodeCorrect()
}
override func viewDidLoad() {
super.viewDidLoad()
continueToTimeControlView.isHidden = true
var x_axis = 37
var y_axis = 225
var z = 0
var rangeNumbers = ["1","2","3","4","5","6","7","8","9","<- ","0","OK"]
var btn_create = UIButton();
for _ in 1...4 {
for _ in 1...3 {
btn_create = UIButton(frame: CGRect(x: x_axis, y: y_axis, width: 90, height: 90))
btn_create.setTitle(rangeNumbers[z], for: .normal)
//btn_create?.backgroundColor = UIColor.lightGray
btn_create.setTitleColor(UIColor.black, for: .normal)
btn_create.layer.borderColor = UIColor.lightGray.cgColor
btn_create.layer.borderWidth = 1
btn_create.layer.cornerRadius = 45
btn_create.tag = z
btn_create.addTarget(attendanceView, action: #selector(btnAction), for: .touchUpInside)
self.view.addSubview(btn_create)
x_axis += 105
z += 1
}
x_axis = 37
y_axis += 100
}
}
var pinCode = [Int]()
var pinCodeCounter = 0
func pinCodeLabel() {
pinCodeCounter += 1
if pinCodeCounter == 1 {
pinLabel.text = "*"
}
if pinCodeCounter == 2 {
pinLabel.text = "**"
}
if pinCodeCounter == 3 {
pinLabel.text = "***"
}
if pinCodeCounter == 4 {
pinLabel.text = "****"
}
if pinCodeCounter == 0 {
pinLabel.text = ""
}
}
#IBOutlet weak var pinLabel: UILabel!
#IBOutlet weak var pinCodeCheck: UILabel!
#IBOutlet weak var continueToTimeControlView: UIButton!
#IBAction func pinCodeCorrect() {
if pinCode == [8, 1, 1, 8] {
pinCodeCheck.text = "PIN-Code Richtig"
pinCodeCheck.textColor = UIColor.black
continueToTimeControlView.isHidden = false
} else {
pinCodeCheck.text = "PIN-Code Falsch"
pinCodeCheck.textColor = UIColor.red
}
}
let btn_create = UIButton(type: .system)
#IBOutlet weak var attendanceView: UIView!
func btnAction(sender: UIButton!) {
switch (sender.tag) {
case 0:
pinCode.append(1)
print("1")
case 1:
pinCode.append(2)
print("2")
case 2:
pinCode.append(3)
print("3")
case 3:
pinCode.append(4)
print("4")
case 4:
pinCode.append(5)
print("5")
case 5:
pinCode.append(6)
print("6")
case 6:
pinCode.append(7)
print("7")
case 7:
pinCode.append(8)
print("8")
case 8:
pinCode.append(9)
print("9")
case 9:
pinCode.removeAll()
print("<-")
case 10:
pinCode.append(0)
print("0")
case 11:
pinCodeCorrect()
print(pinCode)
print("OK")
default:
print("")
}
pinCodeCorrect()
}
override func viewDidLoad() {
super.viewDidLoad()
continueToTimeControlView.isHidden = true
var x_axis = 37
var y_axis = 225
var z = 0
var rangeNumbers = ["1","2","3","4","5","6","7","8","9","<-","0","OK"]
var btn_create = UIButton();
for _ in 1...4 {
for _ in 1...3 {
btn_create = UIButton(frame: CGRect(x: x_axis, y: y_axis, width: 90, height: 90))
btn_create.setTitle(rangeNumbers[z], for: .normal)
//btn_create?.backgroundColor = UIColor.lightGray
btn_create.setTitleColor(UIColor.black, for: .normal)
btn_create.layer.borderColor = UIColor.lightGray.cgColor
btn_create.layer.borderWidth = 1
btn_create.layer.cornerRadius = 45
btn_create.tag = z
btn_create.addTarget(attendanceView, action: #selector(btnAction), for: .touchUpInside)
self.view.addSubview(btn_create)
x_axis += 105
z += 1
}
x_axis = 37
y_axis += 100
}
}
}

How to Render a Pie Chart on childviews in iOS?

How to render pie charts on child views? In my story board having 4 child views. I am trying to show 4 different pie charts based on the selection ( I am using segmented control which has 4 segments ). I tried with sample data but not able to render pie chart ( as it showing no data available ). How to add pie chart data to child views?
[ Note:- I am using danielgindib library and swift 3 ]
Screenshot of my storyboard
Storyboard screenshot 1
Storyboard screenshot 2
SecondViewController.swift
import UIKit
import Charts
class SecondViewController: UIViewController, ChartViewDelegate{
var controllerName:String?
#IBOutlet weak var pChartViewA: PieChartView!
#IBOutlet weak var pChartViewB: PieChartView!
#IBOutlet weak var pChartViewC: PieChartView!
#IBOutlet weak var pChartViewD: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
self.pChartViewA.delegate = self
// self.pChartViewB.delegate = self
//self.pChartViewC.delegate = self
// self.pChartViewD.delegate = self
self.pChartViewA.alpha = 1
//self.pChartView.delegate = self
// Pie Chart
pChartViewA.noDataText = "You need to provide data for the chart."
let pys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) * 100.0 }
let pyse1 = pys1.enumerated().map { x, y in return PieChartDataEntry(value: y, label: String(x)) }
let pdata = PieChartData()
let pds1 = PieChartDataSet(values: pyse1, label: "Hello")
pds1.colors = ChartColorTemplates.vordiplom()
pdata.addDataSet(pds1)
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
let centerText: NSMutableAttributedString = NSMutableAttributedString(string: "Sample Screening Pie")
self.pChartViewA.centerAttributedText = centerText
self.pChartViewA.data = pdata
self.pChartViewA.chartDescription?.text = "Piechart Demo"
}
#IBAction func ChangeComponent(_ sender: AnyObject) {
if sender.selectedSegmentIndex == 0 {
UIView.animate(withDuration: 0.5, animations: {
self.pChartViewA.alpha = 1
self.pChartViewB.alpha = 0
self.pChartViewC.alpha = 0
self.pChartViewD.alpha = 0
// Pie Chart
self.pChartViewA.noDataText = "You need to provide data for the chart."
let pys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) * 100.0 }
let pyse1 = pys1.enumerated().map { x, y in return PieChartDataEntry(value: y, label: String(x)) }
let pdata = PieChartData()
let pds1 = PieChartDataSet(values: pyse1, label: "Hello")
pds1.colors = ChartColorTemplates.vordiplom()
pdata.addDataSet(pds1)
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
let centerText: NSMutableAttributedString = NSMutableAttributedString(string: "Sample Screening Pie")
self.pChartViewA.centerAttributedText = centerText
self.pChartViewA.data = pdata
self.pChartViewA.chartDescription?.text = "Piechart Demo"
})
} else if sender.selectedSegmentIndex == 1 {
UIView.animate(withDuration: 0.5, animations: {
self.pChartViewA.alpha = 0
self.pChartViewB.alpha = 1
self.pChartViewC.alpha = 0
self.pChartViewD.alpha = 0
})
}
else if sender.selectedSegmentIndex == 2 {
UIView.animate(withDuration: 0.5, animations: {
self.pChartViewA.alpha = 0
self.pChartViewB.alpha = 0
self.pChartViewC.alpha = 1
self.pChartViewD.alpha = 0
})
}
else if sender.selectedSegmentIndex == 3 {
UIView.animate(withDuration: 0.5, animations: {
self.pChartViewA.alpha = 0
self.pChartViewB.alpha = 0
self.pChartViewC.alpha = 0
self.pChartViewD.alpha = 1
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thank you in advance.

Resources