I have collectionView inside a view controller. Inside the collectionView cell I have a button. Since there will be several cells each button will have a different location inside the vc. When a button is tapped, how can I get the frame of the button inside the ViewController (not the collectionView)? I want to get it from within the cell itself and not in cellForItem.
No matter which button I tap inside any cell, I tried this below but it always prints out (0.0, 64.0, 0.0, 0.0)
:
@objc func myButtonTapped() {
let locationInSuperView = self.convert(myButton.frame, to: nil)
print(locationInSuperView)
}
Code below:
CollectionViewCell:
class MyCell: UICollectionViewCell{
lazy var myButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "myButton"), for: .normal)
button.addTarget(self, action: #selector(myButtonTapped), for: .touchUpInside)
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
contentView.addSubview(myButton)
myButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
myButton.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
myButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
}
@objc func myButtonTapped() {
let locationInSuperView = self.superview!.convert(myButton.frame, to: nil)
print(locationInSuperView)
}
}
ViewController:
ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var collectionView: UICollectionView!
let myCell = "myCell"
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.scrollDirection = .vertical
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(MyCell.self, forCellWithReuseIdentifier: myCell)
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: myCell, for: indexPath) as! MyCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 50)
}
}
convert
? – Kerberos