ios - 自定义 UIView 委托
问题描述
我是 swift 和 ios 开发的新手。我正在创建一个UIView
由 a 组成的tableView
,我将使用它来显示信息供用户选择,类似于选择器,但它是 atableView
并且它占据了整个屏幕。
class SelectView: UIView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit(){
Bundle.main.loadNibNamed("SelectView", owner: self, options: nil)
//contentView.frame = self.bounds
//contentView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
tableView.dataSource = self
tableView.delegate = self
self.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let cell = UITableViewCell()
print("cell ", String(indexPath.row))
cell.textLabel?.text = "test"
return cell
}
}
然后在我的另一堂课中,我正在尝试这样做
let pickerView = SelectView()
pickerView.delegate = self
pickerView.datasource = self
textfield.inputView = pickerView
我认为这应该可以工作,但是会覆盖我放在 中的默认值SelectView
,但是我收到了这个错误。
“ ”类型的值SelectView
没有成员“ delegate
”并且无法分配给属性:“ inputView
”是仅获取属性。
不确定这里发生了什么,但似乎我已经委派了安全措施,然后只是用文本字段告诉班级委派。
解决方案
以这种方式检查,
import UIKit
public protocol menuOpen: class {
func openMenuAction(selectedValue : String)
}
class SelectView: UIView {
open var delegate:menuOpen?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.delegate.openMenuAction("test")
}
}
现在在你的另一个班级
确保在你的另一个班级确认你的协议
class HomeViewController: UIViewController,menuOpen{
override func viewWillAppear(_ animated: Bool) {
let pickerView = SelectView()
pickerView.delegate = self
textfield.inputView = pickerView
}
func openMenuAction(selectedValue : String) {
//get your selected value here, you would better pass parameter in this method
}
}
推荐阅读
- javascript - 如何在没有客户端 JavaScript 的情况下使用 JSON 数据呈现静态 HTML?
- hadoop - 在哪些情况下我们不会为文件分配块?
- c - 指针还是地址?
- java - 正则表达式否定模式
- ios - Swift - WKWebKit - 无法在外部浏览器(Safari)中打开链接
- javascript - Javascript/JQuery 如果 cookie 不存在 接受
- wordpress - 带有 wp_list_comments() 的 Wordpress 评论顺序
- automationanywhere - Web 元素上的“设置文本”操作间歇性地生成 TYPE_021 错误
- python - 如何对熊猫中的两组列执行元素明智的操作
- data-structures - 处理大型数组上的大量查询的数据结构