Reputation: 2024
Maybe it is the wrong idea completely to use the same xib multiple times in one viewcontroller, but it looked in some way better than creating an x amount of views with the same labels and the same buttons.. And of course some fun with xibs:)
To give you a quick impression of what I achieved so far:
In the class belonging to the xib, I created a delegate so I could catch a button press in my main view controller.
import UIKit
protocol TimerViewDelegate : class {
func timerButtonTapped(buttonState : NSInteger)
}
class TimerView: UIView {
var delegate : TimerViewDelegate?
var currentButtonState = 0
@IBOutlet var view: UIView!
@IBOutlet var timerLabel: UILabel!
@IBOutlet var button: UIButton!
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
NSBundle.mainBundle().loadNibNamed("TimerView", owner: self, options: nil)
self.addSubview(self.view)
}
@IBAction func buttonTapped(sender:UIButton) {
if currentButtonState == 0{
currentButtonState = 1
} else{
currentButtonState = 0
}
self.delegate?.timerButtonTapped(currentButtonState)
}
}
I know it is not super fancy stuff, but at the moment I'm only evaluating if its any use to do this at all.
In my main view controller I registered outlets for the xibs in a way like:
@IBOutlet weak var timerView1 : TimerView!
@IBOutlet weak var timerView2 : TimerView!
@IBOutlet ...
And in viewDidLoad():
self.timerView1.delegate = self
self.timerView2.delegate = self
self...
Later I can catch the button presses in the following method:
func timerButtonTapped(buttonState: NSInteger) {
println("button press from nib, with state \(buttonState)")
}
From here it does make a difference if I press the button from the top xib or another one, since they keep track of their own buttonstate. But how can I distinguish the different xibs from each other like this?
I can give the xibs themselves a tag, but I don't know if that has any use. Also talking to their labels from my main view, will have a simular problem..
Even if this is a completely wrong approach of using xibs, I'm still interested how to solve this. Thank you for your time!
Upvotes: 0
Views: 976
Reputation: 119041
You pretty much have your solution already, you just need to improve your protocol method specification, basically by adding the TimerView
that is passing on the button press.
(compare to a delegate protocol like UITableViewDelegate
, where the table view always passes itself...)
So, something like:
protocol TimerViewDelegate : class {
func timerButtonTapped(sender: TimerView, buttonState : NSInteger)
}
and then the delegate can find out which TimerView
is associated and do something with it.
Incidentally, it's likely best to store the TimerView
instances in an array, sorted in some way, so that you can easily access the details.
Upvotes: 1
Reputation: 1936
You can use the tag property safely. Apple documentation says:
An integer that you can use to identify view objects in your application.
Upvotes: 0