我试图在UIAction中为我的菜单项在UIKit中使用动作。所以,对于第一个按钮,我无法应用动作。它显示了错误“无法在范围内找到‘动作’”。
我真的很想在这种情况下使用选择器。我想知道对选择器采取行动的最佳方式是什么
class MessageViewController : UIViewController, UITableViewDelegate {
private lazy var first = UIAction(title: "Edit", image: UIImage(systemName: "pencil.circle"), attributes: [], state: .off) { [self]_ in
action: #selector(self.RightSideBarButtonItemTapped(_:))
}
private lazy var second = UIAction(title: "Second", image: UIImage(systemName: "pencil.circle"), attributes: [.destructive], state: .on) { action in
print("Second")
#selector(self.sendMessageRightSideBarButtonItemTapped(_:))
}
private lazy var third = UIAction(title: "Third", image: UIImage(systemName: "pencil.circle"), attributes: [], state: .off) { action in
print("third")
}
private lazy var elements: [UIAction] = [first]
private lazy var menu = UIMenu(title: "new", children: elements)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
menu = menu.replacingChildren([first, second, third])
if #available(iOS 14.0, *) {
navigationItem.rightBarButtonItem?.menu = menu
}
}从“Hangar Rash”尝试解决方案
private lazy var first = UIAction(title: "Edit", image: UIImage(systemName: "pencil.circle"), attributes: [], state: .off)
{ [unowned self] action in
self.RightSideBarButtonItemTapped(_:)
// Getting error on this line which says its " Function is unused "
}
override func viewDidLoad() {}
override func viewDidAppear(_ animated: Bool) {}
@objc func RightSideBarButtonItemTapped(_ sender:UIBarButtonItem!)
{
let vc = IceWorldView()
present(vc, animated: true)
}发布于 2022-11-04 00:27:37
你的第一个行动有两个问题:
action
#selector.只需直接调用方法更改:
private lazy var first = UIAction(title: "Edit", image: UIImage(systemName: "pencil.circle"), attributes: [], state: .off) { [self]_ in
action: #selector(self.RightSideBarButtonItemTapped(_:))
}至:
private lazy var first = UIAction(title: "Edit", image: UIImage(systemName: "pencil.circle"), attributes: [], state: .off) { [unowned self] action in
self.RightSideBarButtonItemTapped(someButton)
}RightSideBarButtonItemTapped需要一个UIBarButtonItem参数,但菜单中没有一个参数。您可以创建一个虚拟按钮实例来传入,也可以更改RightSideBarButtonItemTapped,这样它就不会接受任何参数。不管怎么说,你似乎并没有使用传递的发送者。
在第二个操作中也修正了#selector的使用。
https://stackoverflow.com/questions/74310257
复制相似问题