ios - 如何将 UICollectionView 添加到 inputAccessoryView

标签 ios swift uicollectionview inputaccessoryview

我想将 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
}

最佳答案

添加一个 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配置数据。

enter image description here

关于ios - 如何将 UICollectionView 添加到 inputAccessoryView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56278436/

相关文章:

objective-c - 当 ViewController 从 UIStoryboard 实例化时,isMemberOfClass 返回 no

ios - 带有后退按钮的导航栏不隐藏

ios - 检测 UIbuttons 是否重叠

swift - 表达式类型 'SocketIOClientConfigutation' 在没有更多上下文的情况下不明确

ios - 解析 Swift : User relations with a "friends request"

swift - UICollection View 中的搜索栏不是搜索结果

ios - 使用 "performSegueWithIdentifier"发送值时目标值为空

swift - 滚动tableview重置水平 ScrollView 页面控件

ios - UICollectionViewController 的自定义弹出动画不起作用

ios - UIView 在滚动时从 UICollectionView 的底部分离