【发布时间】:2016-10-06 07:55:00
【问题描述】:
我正在尝试使用 0 到 9 的数字输入自定义密码,并像这样随机放置一些空键:
这是我的简单 UICollectionViewCell
class KeyboardKeyCollectionViewCell: UICollectionViewCell {
@IBOutlet var mLabel: UILabel!
}
我的 UIView 包含 UICollectionView(作为测试,我只尝试使用 3 个单元格)
import UIKit
protocol KeyboardDelegate: class {
func keyWasTapped(character: String)
}
class PasswordKeyboard: UIView , UICollectionViewDataSource , UICollectionViewDelegate {
@IBOutlet var mCollectionView: UICollectionView!
weak var delegate: KeyboardDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeSubviews()
}
func initializeSubviews() {
let lBundle = Bundle(for: type(of: self))
let lKeyboardNib = UINib(nibName: "PasswordKeyboard", bundle: lBundle)
let lCellNib = UINib(nibName: "KeyboardKeyCollectionViewCell", bundle: lBundle)
let lKeyboardNibView = lKeyboardNib.instantiate(withOwner: self, options: nil).first as! UIView
self.addSubview(lKeyboardNibView)
lKeyboardNibView.frame = self.bounds
mCollectionView.dataSource = self
mCollectionView.delegate = self
mCollectionView.register(lCellNib, forCellWithReuseIdentifier: "idgaf")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "idgaf", for: indexPath as IndexPath) as! KeyboardKeyCollectionViewCell
cell.mLabel.text = String(describing: indexPath.item) //TODO Randomize this
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "idgaf", for: indexPath as IndexPath) as! KeyboardKeyCollectionViewCell
self.delegate?.keyWasTapped(character: cell.mLabel.text!)
}
}
以及带有将使用该自定义键盘的文本字段的 ViewController
class LoginController: UiViewController , KeyboardDelegate
{
func keyWasTapped(character: String) {
passwordField.insertText(character)
}
override func viewDidLoad()
{
super.viewDidLoad()
let keyboardView = PasswordKeyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300))
keyboardView.delegate = self
passwordField.inputView = keyboardView
}
}
我目前所做的并没有使我的应用程序崩溃,视图按原样显示,并且委托被调用是它应该但是我丢失了我单击的单元格的引用。
在创建单元格的过程中,我从调试器中获得了一些日志:
点击第一个单元格后:
我一直在尝试解决此问题,但找不到导致此问题的原因。感谢您阅读直到此。
【问题讨论】:
标签: ios xcode uicollectionview swift3