Individual Labels update value when swiped - ios

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]!)”
}

Related

How to Animate UIView on a line path without using UIBezierPath?

I have draw UIView say rectangle(player) and line, using context using draw(_ rect: CGRect) method.
I want to move the player on a line when clicking the play button.
I have searched lots of, but I found only for UIBezierpath but I want to use it with context
and I have tried some code name with playAnimation function.
class CanvasView : UIView{
// straight line
var lineStartPoint = CGPoint()
var lineEndpoint = CGPoint()
var lineStrokeList = [Lines]()
var lineDict : [String : Lines] = [:]
var lineActionDictionary : [String : [String : Lines]] = [:]
var linesPath : CGPath?
//player
var playerPoint : CGPoint?
var playerList = [Players]()
var playerDict : [Int : Players] = [:]
var selectedPlayerNumber : Int = 0
//action
var actionDict : [String : String] = ["1" : "1"]
var actionKeyIndex = String()
var actionList : [String] = [String]()
// common
var strokeWidth : CGFloat = 2.0
var currentColor = UIColor.black.cgColor
var imageSize : CGFloat = 30.0
private var selectedShape : ShapeType = .player
//MARK: Touches Began
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
switch selectedShape {
case .player:
playerPoint = touch.location(in: self)
playerDict.forEach { (key,value) in
if value.rect.contains(playerPoint ?? CGPoint()){
selectedPlayerNumber = Int(key)
self.playerDict.removeValue(forKey: selectedPlayerNumber)
return
}
}
setNeedsDisplay()
case .line:
let pos = touch.location(in: self)
lineStartPoint = pos
lineEndpoint = pos
setNeedsDisplay()
}
}
//MARK: Touches Moved
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let isfreeDrawSelected = isfreeDrawSelected
switch selectedShape {
case .player:
playerPoint = touch.location(in: self)
setNeedsDisplay()
case .line:
lineEndpoint = touch.location(in: self)
setNeedsDisplay()
}
}
//MARK: Touches Ended
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
switch selectedShape {
case .player:
if playerPoint != nil {
let point = CGPoint(x: playerPoint!.x, y: playerPoint!.y)
let x = playerPoint!.x - 15
let y = playerPoint!.y - 15
let playerRect = CGRect(x: x, y: y, width: imageSize, height: imageSize)
let playerstruct = Players(point: point,rect: playerRect)
playerList.append(playerstruct)
playerDict[selectedPlayerNumber] = playerstruct
playerPoint = nil
selectedPlayerNumber += 1
setNeedsDisplay()
}
case .line:
lineEndpoint = touch.location(in: self)
if !playerDict.isEmpty{
if lineActionDictionary[actionKeyIndex]?[String(selectedPlayerNumber)] != nil{
let alert = UIAlertController(title: "", message: "You can't add mutiple lines for action \(actionKeyIndex)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { alertAction in
debugPrint(self.lineActionDictionary)
}))
UIApplication.shared.windows
.last?.rootViewController?
.present(alert, animated: false, completion: nil)
}
else{
let line = Lines(startPoint: lineStartPoint, endPoint: lineEndpoint, color: currentColor, width: strokeWidth)
lineStrokeList.append(line)
lineDict[String(selectedPlayerNumber)] = line
if lineActionDictionary[actionKeyIndex] != nil {
lineActionDictionary[actionKeyIndex]!.updateValue(line, forKey: String(selectedPlayerNumber))
}else{
lineActionDictionary[actionKeyIndex] = lineDict
}
}
lineStartPoint = CGPoint()
lineEndpoint = CGPoint()
lineDict.removeAll()
setNeedsDisplay()
}
}
}
//MARK: Draw
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
if playerPoint != nil {
let x = (playerPoint?.x)! - 15
let y = (playerPoint?.y)! - 15
let player = CGRect(x: x, y: y, width: imageSize, height: imageSize)
context.addRect(player)
context.drawPath(using: .stroke)
linesPath = context.path
}
if !playerDict.isEmpty{
playerDict.forEach { (key,value) in
let x = value.point.x - 15
let y = value.point.y - 15
let player = CGRect(x: x, y: y, width: imageSize, height: imageSize)
let colorView = UIView(frame: player)
context.addRect(player)
context.drawPath(using: .stroke)
}
}
if lineStartPoint.x > 0 && lineEndpoint.y > 0{
context.setLineCap(.round)
context.setLineWidth(2.0)
context.move(to: lineStartPoint)
context.addLine(to: lineEndpoint)
context.setStrokeColor(UIColor.black.cgColor)
context.strokePath()
}
if !lineActionDictionary.isEmpty{
lineActionDictionary.forEach { (actionkey,actionvalue) in
actionvalue.forEach { (playerkey,playervalue) in
let startPoint = playervalue.startPoint
let endPoint = playervalue.endPoint
let color = playervalue.color
let width = playervalue.width
context.setLineCap(.round)
context.setLineWidth(width)
context.move(to: startPoint)
context.addLine(to: endPoint)
context.setStrokeColor(color)
context.strokePath()
}
}
}
}
func selectedShape(selctedShapes : ShapeTypes) {
selectedShape = selctedShapes
}
func playAnimation(){
switch selectedShape {
case .player:
break
case .line:
let player = playerList.first
let views = UIView(frame: player!.rect)
views.alpha = 1.0
UIView.animate(withDuration: 0.25, animations: {
views.frame = CGRect(x: 0, y: 10, width: 20, height: 20)
}, completion: {
(value: Bool) in
debugPrint(">>> Animation done.")
})
}
}
}
#ShapeTypes Enum
enum ShapeTypes : Int {
case player = 0
case line
}
#UIViewController
#available(iOS 14.0, *)
class TestVC : UIViewController{
#IBOutlet weak var colorPicker: UIImageView!
#IBOutlet weak var sliderMaxValueLbl: UILabel!
#IBOutlet weak var radiusSlider: UISlider!
#IBOutlet weak var tv: CanvasView!
#IBOutlet weak var shapeSegment : UISegmentedControl!
#IBOutlet weak var playerFormationPickerDoneBtn: UIButton!
#IBOutlet weak var playerFormationPicker: UIPickerView!
#IBOutlet weak var playerFormationTF: UITextField!
#IBOutlet weak var actionPickerDoneBtn: UIButton!
#IBOutlet weak var actionPicker: UIPickerView!
#IBOutlet weak var actionPickerTF: UITextField!
#IBOutlet weak var addActionBtn: UIBarButtonItem!
//playerformation pickerview
var playerFormationPickerData = String()
var playerFormationPickerSelectedIndex = Int()
var isPlayerFormationSelected : Bool = false
var playerViewArray: [PlayerView] = []
var pickerViewListData: [String] = [String]()
//action pickerview
var actionPickerData = String()
var actionPickerSelectedIndex = Int()
#IBAction func actionPickerDoneButtonAction(_ sender: UIButton) {
actionPickerDoneBtn.isHidden = true
actionPicker.isHidden = true
actionPickerTF.text = actionPickerData
tv.actionKeyIndex = actionPickerTF.text?.components(separatedBy: " ").last ?? ""
debugPrint(tv.actionKeyIndex)
}
func setSliderThumb(_ color: UIColor, _ width : CGFloat) {
let circleImage = makeCircleWith(size: CGSize(width: width, height: width),
backgroundColor: color)
radiusSlider.setThumbImage(circleImage, for: .normal)
radiusSlider.setThumbImage(circleImage, for: .highlighted)
}
fileprivate func makeCircleWith(size: CGSize, backgroundColor: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(backgroundColor.cgColor)
context?.setStrokeColor(UIColor.black.cgColor)
let bounds = CGRect(origin: .zero, size: size)
context?.addEllipse(in: bounds)
context?.drawPath(using: .fill)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
#IBAction func radiusSliderAction(_ sender: UISlider) {
let radius = Int(radiusSlider.value)
tv.radius = CGFloat(radius)
sliderMaxValueLbl.text = String(radius)
}
#IBAction func playAnimationAction(_ sender: UIBarButtonItem) {
tv.playAnimation()
}
override func viewDidLoad() {
super.viewDidLoad()
radiusSlider.minimumValue = 30
radiusSlider.maximumValue = 100
radiusSlider.value = 0
sliderMaxValueLbl.text = String(Int(radiusSlider.value))
setSliderThumb(UIColor.white, 20)
if let img = UIImage(named: "ground") { //background image
UIGraphicsBeginImageContext(tv.frame.size)
img.draw(in: tv.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image {
tv.backgroundColor = UIColor(patternImage: image)
tv.contentMode = .scaleAspectFill
}
}
actionPicker.delegate = self
actionPicker.dataSource = self
actionPicker.isHidden = true
actionPickerTF.delegate = self
actionPickerTF.textAlignment = .center
actionPickerTF.placeholder = "Select action"
actionPickerDoneBtn.isHidden = true
actionPickerDoneBtn.tintColor = .systemBlue
tv.actionKeyIndex = tv.actionDict["1"] ?? ""
tv.actionList = ["action \(tv.actionKeyIndex)"]
actionPickerData = tv.actionList[0]
actionPickerTF.text = actionPickerData
tv.currentColor = UIColor.black.cgColor
}
#IBAction func addActionButton(_ sender: UIBarButtonItem) {
let count = tv.actionList.count + 1
let element = tv.lineActionDictionary.keys.max()
// let element = tv.actionDict.values.max() // find max dict value
guard let maxValue = element?.first?.wholeNumberValue else { return }
debugPrint(maxValue)
tv.actionKeyIndex = String(maxValue + 1)
actionPickerTF.text = "action \(tv.actionKeyIndex)"
tv.actionList.append("action \(tv.actionKeyIndex)")
actionPicker.reloadAllComponents()
}
#IBAction func selectShapeSegmentAction(_ sender: UISegmentedControl) {
let selectShape : ShapeType = ShapeTypes(rawValue: shapeSegment.selectedSegmentIndex) ?? .player
tv.selectedShape(selctedShape: selectShape)
}
}
#available(iOS 14.0, *)
extension TestVC : UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == actionPicker{
actionPickerData = tv.actionList[row]
actionPickerTF.text = actionPickerData
actionPickerSelectedIndex = actionPicker.selectedRow(inComponent: 0)
}
}
}
#available(iOS 14.0, *)
extension TestVC : UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return tv.actionList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return tv.actionList[row]
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var title = UILabel()
if let view = view {
title = view as! UILabel
}
if pickerView == actionPicker {
title.text = tv.actionList[row]
}
title.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
title.textColor = UIColor.black
title.textAlignment = .center
return title
}
}
Lets say you have some customView and you want to simply temporary move it a little bit down. Here is lightweight solution.
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
func animateGoingDown() {
UIView.animate(withDuration: 0.5) {
self.customView.transform = CGAffineTransform(translationX: 0, y: 200)
}
}
func animateGoingToOriginalPosition() {
UIView.animate(withDuration: 0.5) {
self.customView.transform = .identity
}
}
Howefully this is what you are searching for. If you have some questions, do not hesitate to ask.

How to loop a Slider value for height?

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"
}
}

How to attach multiple UIDynamicItems to each other

I am trying to implement circles attached to each other like in Apple's Music App via UIDynamicAnimator. I need to attach circles to each other and to view center. I was trying to implement this via UIAttachmentBehavior, but seems to it's not supporting multiple attachments. In result, circles overlaps on each other :)
let attachment = UIAttachmentBehavior(item: circle, attachedToAnchor: CGPoint(x: view.center.x, y: view.center.y))
attachment.length = 10
animator?.addBehavior(attachment)
let push = UIPushBehavior(items: [circle], mode: .continuous)
collision.addItem(circle)
animator?.addBehavior(push)
What I am doing wrong?
I don't think the apple music genre picker thing uses UIAttachmentBehavior which is closer to attaching two views with a pole or a rope. But, it seems like the problem you're experiencing might be that all of the views are added at the same location which has the effect of placing them on top of each other and with the collision behavior causes them to be essentially be stuck together. One thing to do is to turn on UIDynamicAnimator debugging by calling animator.setValue(true, forKey: "debugEnabled").
For recreating the above circle picker design, I would look into using UIFieldBehavior.springField().
For example:
class ViewController: UIViewController {
lazy var animator: UIDynamicAnimator = {
let animator = UIDynamicAnimator(referenceView: view)
return animator
}()
lazy var collision: UICollisionBehavior = {
let collision = UICollisionBehavior()
collision.collisionMode = .items
return collision
}()
lazy var behavior: UIDynamicItemBehavior = {
let behavior = UIDynamicItemBehavior()
behavior.allowsRotation = false
behavior.elasticity = 0.5
behavior.resistance = 5.0
behavior.density = 0.01
return behavior
}()
lazy var gravity: UIFieldBehavior = {
let gravity = UIFieldBehavior.springField()
gravity.strength = 0.008
return gravity
}()
lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.didPan(_:)))
return panGesture
}()
var snaps = [UISnapBehavior]()
var circles = [CircleView]()
override func viewDidLoad() {
super.viewDidLoad()
view.addGestureRecognizer(panGesture)
animator.setValue(true, forKey: "debugEnabled")
addCircles()
addBehaviors()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gravity.position = view.center
snaps.forEach {
$0.snapPoint = view.center
}
}
func addCircles() {
(1...30).forEach { index in
let xIndex = index % 2
let yIndex: Int = index / 3
let circle = CircleView(frame: CGRect(origin: CGPoint(x: xIndex == 0 ? CGFloat.random(in: (-300.0 ... -100)) : CGFloat.random(in: (500 ... 800)), y: CGFloat(yIndex) * 200.0), size: CGSize(width: 100, height: 100)))
circle.backgroundColor = .red
circle.text = "\(index)"
circle.textAlignment = .center
view.addSubview(circle)
gravity.addItem(circle)
collision.addItem(circle)
behavior.addItem(circle)
circles.append(circle)
}
}
func addBehaviors() {
animator.addBehavior(collision)
animator.addBehavior(behavior)
animator.addBehavior(gravity)
}
#objc
private func didPan(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: sender.view)
switch sender.state {
case .began:
animator.removeAllBehaviors()
fallthrough
case .changed:
circles.forEach { $0.center = CGPoint(x: $0.center.x + translation.x, y: $0.center.y + translation.y)}
case .possible, .cancelled, .failed:
break
case .ended:
circles.forEach { $0.center = CGPoint(x: $0.center.x + translation.x, y: $0.center.y + translation.y)}
addBehaviors()
#unknown default:
break
}
sender.setTranslation(.zero, in: sender.view)
}
}
final class CircleView: UILabel {
override var collisionBoundsType: UIDynamicItemCollisionBoundsType {
return .ellipse
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height * 0.5
layer.masksToBounds = true
}
}
For more information I would watch What's New in UIKit Dynamics and Visual Effects from WWDC 2015

Use my Swipe gesture function on multiple UILabels swift

Im a newbie, ive managed to find and adapt code so that when i swipe a label, the value of that label changes. Now my func only relates to one particular label, but i want to make multiple labels have the exact same function, its a statistic taking label, how do i modify/apply the func to many different labels?
Here is my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var counterLabel: UILabel!
#IBOutlet weak var kickLabel: UILabel!
var counter = 0
var swipeGesture = UISwipeGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
let direction: [UISwipeGestureRecognizerDirection] = [.up, .down, .left, .right]
for dir in direction{
swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.counterLabel(_:)))
counterLabel.addGestureRecognizer(swipeGesture)
swipeGesture.direction = dir
counterLabel.isUserInteractionEnabled = true
counterLabel.isMultipleTouchEnabled = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#objc func counterLabel(_ sender:UISwipeGestureRecognizer){
UIView.animate(withDuration: 1.0) {
if sender.direction == .right{
print("Swiped Right")
self.counter += 1
print(self.counter)
self.counterLabel.text = String(self.counter)
}else if sender.direction == .left{
print("Swiped Left")
print(self.counter)
self.counter -= 1
self.counterLabel.text = String(self.counter)
}else if sender.direction == .up{
print("Swiped Up")
self.counter += 5
self.counterLabel.text = String(self.counter)
}else if sender.direction == .down{
print("Swiped Down")
self.counter = 0
self.counterLabel.text = String(self.counter)
}
}
}
}
UISwipeGestureRecognizer has the view the gesture is applied to. Cast this to a UILabel.
(You might also want to check the gesture state for better performance.)
class ViewController: UIViewController {
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
var counters: [UILabel: Int] = [:]
override func viewDidLoad() {
super.viewDidLoad()
for label: UILabel in [label1, label2] {
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)
}
}
}
#objc func didSwipe(_ gestureRecognizer: UISwipeGestureRecognizer) {
guard gestureRecognizer.state == .recognized else { return }
guard let label = gestureRecognizer.view as? UILabel else { return }
debugPrint("\(gestureRecognizer.direction)")
switch gestureRecognizer.direction {
case .up:
counters[label] = counters[label] + 1
label.text = "Up"
case .down:
label.text = "Down"
case .left:
label.text = "Left"
case .right:
label.text = "Right"
default:
label.text = "???"
}
}
}

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
}
}
}

Resources