sova sova - 2 years ago 72
Swift Question

keeping track of newly created subviews

Every time I create a subview I want to update an Int so that I can reference the specific subview later.

For example,

class circularKey: UIView {
var oscID = 0; //init to zero

init(origin: CGPoint) {
oscID = oscID + 1;

Can I have this number update every time I create a new circularKey so that each circularKey has its own unique self.oscID?



I'm now trying to do this from the viewController.swift responsible for adding these subviews.

class ViewController: UIViewController {

var numOscs = 0; //update when we add a new Bosc

func didTap(tapGR: UITapGestureRecognizer) {

numOscs = numOscs + 1
let newCircularKey = circularKeyView(origin: tapPoint, oscIndex: numOscs)


my assumption is that upon every didTap numOscs shall be incremented, but it simply stays at zero. What to do?

Edit2: never mind, it works now :D

I believe the best solution is to have the invoking controller keep track of how many it has made so far. Thanks for the help all

Answer Source

I think the controller adding the subViews should handle allocating a new ID every time (similarly to tagging buttons)

Regardless, if you did want to create a unique identifier for each subview maybe try creating one with CACurrentMediaTime() as the unique identifier


class circularKey: UIView {
var keyID = 0.0; //init to zero

init(origin: CGPoint) {
    keyID = CACurrentMediaTime()


CACurrentMediaTime() returns the amount of time the app has been active to double precision, so hopefully even adding the sub views in a loop should return unique identifiers each time.

I didn't want to convert the number to an int value and screw up the conversion for you in the main answer but I think you could do:

keyID = Int(CACurrentMediaTime()*1000000000) 
//converting to number of nanoseconds since start of the app

Double check this though!

As a side note: don't use NSDate for this as it syncs with a server and could 'hiccup' in its value, which could truly be hard to debug later down the line.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download