gpt4 book ai didi

ios - 如何更改 UIAlertAction 的标题

转载 作者:行者123 更新时间:2023-11-28 13:37:12 25 4
gpt4 key购买 nike

单击按钮时如何更改 UIAlertAction 的标题?例如,我想单击该按钮并从“启用”将其设置为“禁用”。我花了很多时间试图实现这一目标,但我无法做到。这是我的问题的一个小演示:https://github.com/tygruletz/ChangeTitleOfAlertAction

这是我的代码:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

}
}

extension ViewController: UITableViewDelegate, UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 5
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

tableView.tableFooterView = UIView()

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

cell.textLabel?.text = "Row \(indexPath.row)"

return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

showOptions()
}

func showOptions(){

var enable = "Enable"
let disable = "Disable"

let applyOn = UIAlertAction(title: enable, style: .default, handler: { (action: UIAlertAction!) in

enable = disable
})

let actionSheet = configureActionSheet()
actionSheet.addAction(applyOn)

self.present(actionSheet, animated: true, completion: nil)
}

func configureActionSheet() -> UIAlertController {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheet.addAction(cancel)

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
actionSheet.popoverPresentationController?.sourceView = self.view
actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
actionSheet.popoverPresentationController?.permittedArrowDirections = []
}

return actionSheet
}
}

这是屏幕截图:

enter image description here

如果你想帮助我,谢谢你!

最佳答案

请遵循以下代码:

在您的 UIViewController 中定义属性

var selectedIndexPath:IndexPath!

showOptions 方法中添加参数

   func showOptions(indexPath:IndexPath){

var status = "Enable"

if selectedIndexPath == indexPath{
status = "Disable"
}

let applyOn = UIAlertAction(title: status, style: .default, handler: { (action: UIAlertAction!) in
if self.selectedIndexPath == indexPath{
self.selectedIndexPath = nil
}else{
self.selectedIndexPath = indexPath
}
})

let actionSheet = configureActionSheet()
actionSheet.addAction(applyOn)

self.present(actionSheet, animated: true, completion: nil)
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
showOptions(indexPath: indexPath)
}

注意事项:

如果您采用这种方法,那么您将永远不会遇到单元可用性问题。

关于ios - 如何更改 UIAlertAction 的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56461105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com