2

I have my own custom view and adding them dynamically to the UIViewController.

Those views are something like:

class pinView: UIView {


    var userID : String?
    var lastTimeConnected : Date?


    init(userID: String, lastTimeConnected : Date)
    {
        self.userID = userID
self.lastTimeConnected = lastTimeConnected

    }

I then add my view to the UIViewController by calling

 imageView.addSubview(pinViewInstance) in a loop

I have events that will trigger my views to move on the screen. I call a database to get their new position and then I need to update them. How do I get to the view by using the userID on my custom view? I would use tags but they are just INT and I need something much bigger than that. Otherwise I need to map the tags to the userIDs which I really want to avoid.

To be clear... I know I can do this: let pinViewInstance = self.view.viewWithTag(numberHere) as? pinView But what I want is to access it by the ID, the first reason why I extended the UIView class in the first place.

I hope you know how to solve this has been stuck on it for a bit and cannot see a way around it. Your help much appreciated. Thanks!

2 Answers 2

4

Two options:

One: iterate with a for-loop through the UIImageView.subviews that those custom-views had been added to. set each view to a pinView reference and compare the userID in it.

func getPinView(userId: String) -> (pinView?) {
    for view in self.imageView.subviews as [UIView] {
        if let pin = view as? pinView {
            if pin.userID == userId {
                return pin
           }
        }
    }
    return nil
}

Two: when you add the pinView add them to a dictionary with the userId as key. And when you need the pinView. get it with the key:

// init
var pinViews: [String: pinView] = [:]

// after adding subview
pinViews[pinViewInstance.userID] = pinViewInstance

// get pinView
let pin: pinView = pinViews[userID] as! pinView
Sign up to request clarification or add additional context in comments.

1 Comment

This works like a charm. Really good solution, elegant and definitely beats using tag. Exactly what I needed.
1

You can iterate through imageView.subviews and find the pinView by using this class type check:

if type(of: aSubview) == pinView.self

Then you can access the userID and check for the right userID.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.