首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在表视图单元格和.xib中添加预警操作(swift 3)

如何在表视图单元格和.xib中添加预警操作(swift 3)
EN

Stack Overflow用户
提问于 2017-06-16 15:55:49
回答 1查看 1.6K关注 0票数 0

我是斯威夫特世界的超级新手。

我在Main.Storyboard中使用UITableView,在.xib文件中使用UITableViewCell

下面是一些与UITableView相关的ViewController.swift代码:

代码语言:javascript
运行
复制
@IBOutlet weak var friendsTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    friendsTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contacts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    let entry = contacts[(indexPath as NSIndexPath).row]

    cell.configureWithContactEntry(entry)
    cell.layoutIfNeeded()

    return cell
}

以下是与TableViewCell.xib相关的TableViewCell.swift代码。

代码语言:javascript
运行
复制
@IBOutlet weak var contactNameLabel: UILabel!
@IBOutlet weak var contactPhoneLabel: UILabel!

    override func layoutIfNeeded() {
    super.layoutIfNeeded()
}

func configureWithContactEntry(_ contact: ContactEntry) {
    contactNameLabel.text = contact.name
    contactPhoneLabel.text = contact.phone ?? ""

}

而且,在TableViewCell.xib中,我使用了UITableViewCell,2个标签。

在这种情况下,当我按下我的一个表格单元格时,我如何添加AlertAction?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-16 16:09:08

您必须将alertViewController添加到TableViewController,而不是单元格本身。但是,正如您希望在用户触摸单元格时显示警告视图那样,只需实现tableViewDidselectRow并从那里显示您的alertView

代码语言:javascript
运行
复制
 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let alert = UIAlertController(title: "Alert", message: "This is an Alert", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    present(alert, animated: true, completion: nil)
}

现在,通过触摸单元格,它将显示一个警报

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44583859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档