我只能从ViewController中创建我的segue函数,而且我必须在我的TableViewCell中有longPress函数。没有办法在不出现错误的情况下引用segue函数。我将如何在cellForRow中实现这段代码,以便在TableView Cell内按住按钮时进行分离?顺便说一下,我使用的是故事板。
@objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
print("Long Press")
//performSegue(withIdentifier: "toProfile", sender: self)
}
}
func addLongPressGesture(){
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
longPress.minimumPressDuration = 0.75
self.expandButton.addGestureRecognizer(longPress)
我找到了一个简单而又非正统的解决方案,但效果非常好。
在TableView Cell中放置第二个按钮,连接你的segue,并将其设置为隐藏。然后为它创建IBOutlet,我把它命名为SegueButton。
@IBOutlet weak var LongPressButton: UIButton!
@IBOutlet weak var SegueButton: UIButton!
现在添加到你的awakeFromNib中。
override func awakeFromNib() {
addLongPressGesture()
}
最后,添加长按按钮的代码。
@objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
print("Segue was Successful")
SegueButton.sendActions(for: .touchUpInside)
}
}
func addLongPressGesture(){
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
longPress.minimumPressDuration = 0.75
self.LongPressButton.addGestureRecognizer(longPress)
}
}
你需要有一种方法从你的按钮单元格 传回你的视图控制器。我建议使用一个闭包。它看起来像这样(我没有测试过这段代码)......
class SomeCell: UITableViewCell {
var didLongPress: (()->Void)? = nil
@objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
didLongPress?()
}
}
override func prepareForReuse() {
didLongPress = nil
}
}
class TableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellId") as! SomeCell
cell.didLongPress = { [weak self] in
self?.performSegue(withIdentifier: "showDetail", sender: nil)
}
return cell
}
}
我在tableview单元格内设置了按钮,当点击时切换到一个视图控制器,长按时切换到不同的控制器。
1)创建一个委托协议。你可以把这个放在自定义的TableViewCell类文件中,但不能放在类本身的内部。
protocol MyTableViewCellDelegate : class {
func didTapButton ()
func didLongPressButton ()
}
2)在实际的TableViewCell类里面,放入以下内容。
weak var delegate: MyTableViewCellDelegate?
/ 锅炉板代码
@objc func didLongPress(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began {
delegate?.didLongPressButton()
}
}
控制将你的按钮从你的tableview单元格拖到这个文件中。然后添加额外的逻辑。
@IBAction func expandButton(_ sender: Any) {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress))
self.addGestureRecognizer(longPress)
delegate?.didTapButton()
}
在你的主ViewController文件中,在cellForRowAt.Cell中添加以下内容。
cell.delegate = self
然后在ViewController类逻辑之外的某个地方,添加以下内容以符合你的委托协议并执行你的转接。
extension ViewController: MyTableViewCellDelegate {
func didTapButton() {
performSegue(withIdentifier: "toInfoSegue", sender: self)
}
@objc func didLongPressButton() {
performSegue(withIdentifier: "toProfileSegue", sender: self)
}
}