由于您想知道点击了哪个字母,我建议使用集合视图。这是一个示例实现:
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
//Here I am generating an array of 14*14 strings since I don't have access to the randomLetter() function
let elements = (0..<(14 * 14)).map { String($0) }
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(CollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return elements.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
cell.label = UILabel(frame: cell.bounds)
cell.label.text = elements[indexPath.row] //In your case you would use: cell.label.text = randomLetter()
cell.label.font = UIFont(name: "helvetica", size: 10)
cell.label.textAlignment = .center
cell.addSubview(cell.label)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: self.view.frame.size.width/14, height: self.view.frame.size.width/14)
return size
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
print(String(describing: cell.label.text))
}
}
自CollectionViewCell定义UICollectionViewCell定义如下:
class CollectionViewCell: UICollectionViewCell {
var label: UILabel!
}