k.thomas
k.thomas

Reputation: 51

highlight and unhighlight UIView

I want to create a function that will change a UIView background color when it is touched, and when another UIView is selected it will change the originally clicked UIView color back to white. This function is part of a UIView Subclass. The function below changes the background color, but I am struggling to change the 'departing' UIView back to white color.

func viewHighlight () {

    if self.tag == self.tag
    {
        self.backgroundColor = UIColor.lightGray

        self.tintColor = UIColor(named:"tint")

    }else if self.tag != self.tag
    {
        self.backgroundColor = UIColor.white
        self.tintColor = UIColor.black

    }
}

Upvotes: 0

Views: 1251

Answers (2)

iOS Geek
iOS Geek

Reputation: 4855

My View Outlets :

@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView!
@IBOutlet weak var view3: UIView!

I had used Button To explain Your Question

@IBAction func collectionButton(_ sender: UIButton)
    {
        switch sender.tag
        {
        case 1:
            self.setGrayBackground(baseView: view1)
            self.setbackgroundWhite(baseView: view2)
            self.setbackgroundWhite(baseView: view3)
            break
        case 2:
            self.setGrayBackground(baseView: view2)
            self.setbackgroundWhite(baseView: view1)
            self.setbackgroundWhite(baseView: view3)
            break
        case 3:
            self.setGrayBackground(baseView: view3)
            self.setbackgroundWhite(baseView: view2)
            self.setbackgroundWhite(baseView: view1)
            break
        default:
            print("Default Case")
        }
    }

    func setbackgroundWhite(baseView:UIView)
    {
        if baseView.backgroundColor != UIColor.white {
            baseView.backgroundColor = UIColor.white
        }
    }

    func setGrayBackground(baseView:UIView)
    {
        if baseView.backgroundColor != UIColor.lightGray {
            baseView.backgroundColor = UIColor.lightGray
        }
    }

StoryBoard:

With Assigned Button tags

enter image description here

Upvotes: 0

Quoc Nguyen
Quoc Nguyen

Reputation: 3007

You should create a variable in your superView to manager the selected view

var selectedTag: Int = -1 {
    didSet {
        if let subView = superView.viewWithTag(oldValue) {
            subView.backgroundColor = .white
        }
        if let selectedView = superView.viewWithTag(selectedTag) {
            selectedView.backgroundColor = <your_color>
        }
    }
}

Upvotes: 1

Related Questions