如何将 UICollectionView 添加到 inputAccessoryView
Posted
技术标签:
【中文标题】如何将 UICollectionView 添加到 inputAccessoryView【英文标题】:How to add UICollectionView to the inputAccessoryView 【发布时间】:2019-05-23 15:21:36 【问题描述】:我想将UICollectionView
添加到inputAccessoryView
以便滚动列表。
override var inputAccessoryView: UIView?
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 80))
customView.backgroundColor = UIColor.red
return customView
【问题讨论】:
你为什么需要那个? 我有一个单词列表。当用户在文本字段中输入文本时。我必须在集合视图单元格中建议这个列表数组 【参考方案1】:要将UICollectionView
添加为inputAccessoryView
,
1. 首先创建一个包含UICollectionView
的custom UIView
,并向其中添加UICollectionViewDataSource
方法。
class CustomView: UIView, UICollectionViewDataSource
@IBOutlet weak var collectionView: UICollectionView!
let words = ["abscind","downwind","headwind","lind","rescind","sind","skinned","tailwind","thin-skinned","tinned","twinned","upwind","whirlwind","wind"]
override func awakeFromNib()
super.awakeFromNib()
self.collectionView.register(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "cell")
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return self.words.count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
cell.label.text = self.words[indexPath.row]
return cell
class CustomCell: UICollectionViewCell
@IBOutlet weak var label: UILabel!
2. 根据您的要求将上面创建的CustomView
的实例添加为UITextField/UITextView
的inputAccessoryView
。
class ViewController: UIViewController
@IBOutlet weak var textField: UITextField!
override func viewDidLoad()
super.viewDidLoad()
if let customView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? CustomView
self.textField.inputAccessoryView = customView
在上面的代码中,你可以根据需要给collectionView
配置数据。
【讨论】:
由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[new.viewControlller:-collectionView:numberOfItemsInSection:]:无法识别的选择器发送到实例 0x7fd6d249a870' 你当然需要连接outlets
并为CustomView
和CustomCell
创建xib
文件,并在storyboard
中创建controller
和textfield
已连接outlet
。在继续之前你应该做的那件非常基本的事情。
我已经为 customView 和自定义单元创建了 xib 并且还连接到 viewController 。但仍然出现此错误
所有插座都连接了吗?您遇到的问题是 Outlet 问题。交叉检查ViewController
、CustomView
和CustomCell
中的所有网点。
非常感谢妈妈 .. 我找到了问题所在。并解决了。以上是关于如何将 UICollectionView 添加到 inputAccessoryView的主要内容,如果未能解决你的问题,请参考以下文章