Reputation: 33
I have created a label I am trying to turn into a segue to another page, but before I can setup the segue I have to make the label clickable. I have tried numerous different ways that have been mentioned here but cannot seem to get it to work correctly. The way my code is set up, the label is created in an external class associated with a UICollectionView, this class is not in the same swift file that the ViewDidLoad()
function is in.
Here is the creation of the label in the class file inside of its own class that is not related to the file that ViewDidLoad()
is in. The class that the label is in is being called in the ViewDidLoad()
function, so the label and all of its properties are still being displayed.
Creation of label
@IBOutlet weak var moreLabel: UILabel! = {
let label = UILabel()
label.text = "See More..."
label.font = UIFont.italicSystemFont(ofSize: 16)
label.textColor = UIColor.lightGray
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .right
label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapMore))
return label
}()
Function for the click
@objc func tapMore(sender: UITapGestureRecognizer){
print ("You tapped more")
}
Upvotes: 0
Views: 1538
Reputation: 9925
label.frame = CGRect(x: 0, y: 0, width: 100, height: 24)
label.addGestureRecognizer(tap)
Upvotes: 0
Reputation: 77638
You haven't added the gesture recognizer to the label...
EDIT
Even though you haven't added the recognizer to the label, as noted by matt
this won't work anyway, as self
does not exist in this context.
I'm more accustomed to using this format:
//@IBOutlet weak var moreLabel: UILabel! = {
lazy var moreLabel: UILabel = {
let label = UILabel()
label.text = "See More..."
label.font = UIFont.italicSystemFont(ofSize: 16)
label.textColor = UIColor.lightGray
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .right
label.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapMore))
// add it to the label
label.addGestureRecognizer(tap)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(moreLabel)
NSLayoutConstraint.activate([
moreLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
moreLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
@objc func tapMore() -> Void {
print("Tapped")
}
Upvotes: 1
Reputation: 535576
You cannot say target: self
in a property declaration initializer. There is no self
yet. Move all that code into viewDidLoad
.
Upvotes: 1