【问题标题】:How to add UICollectionView to the inputAccessoryView如何将 UICollectionView 添加到 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
}

【问题讨论】:

  • 你为什么需要那个?
  • 我有一个单词列表。当用户在文本字段中输入文本时。我必须在集合视图单元格中建议这个列表数组

标签: ios swift uicollectionview inputaccessoryview


【解决方案1】:

要将UICollectionView 添加为inputAccessoryView

1. 首先创建一个包含UICollectionViewcustom 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/UITextViewinputAccessoryView

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并为CustomViewCustomCell创建xib文件,并在storyboard中创建controllertextfield已连接outlet。在继续之前你应该做的那件非常基本的事情。
  • 我已经为 customView 和自定义单元创建了 xib 并且还连接到 viewController 。但仍然出现此错误
  • 所有插座都连接了吗?您遇到的问题是 Outlet 问题。交叉检查ViewControllerCustomViewCustomCell 中的所有网点。
  • 非常感谢妈妈 .. 我找到了问题所在。并解决了。
猜你喜欢
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 2016-03-14
  • 2014-11-27
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多