gpt4 book ai didi

swift - 创建从 .xib 文件中的 UIButton 到 ViewController 的 Segue

转载 作者:行者123 更新时间:2023-11-30 11:06:12 27 4
gpt4 key购买 nike

在我正在构建的应用程序中,我希望向他们展示用户区域的 map ,其中包含用自定义标记标识的某些地标。当用户点击标记时,会出现一个信息窗口,其中包含一些基本信息和一个显示“获取更多信息”的按钮。目标是当用户单击该按钮时,他们将被带到一个新的 ViewController。

然而,我发现没有内置的方法来隔离 UIView。我已经在 UIView 类上创建了一个协议(protocol)/委托(delegate),但似乎无法真正改变 View 。下面是我的代码:

UIView.swift(信息窗口的 Controller )

import UIKit

protocol MapMarkerDelegate: class {
func didTapInfoButton(data: NSDictionary)
}

protocol MoreButtonTapped: class {
func didClickMoreButton(name: String)
}



class MapMarkerWindow: UIView {
@IBOutlet weak var nameField: UILabel!
@IBOutlet weak var addressField: UILabel!
@IBOutlet weak var openField: UILabel!

var secondDelegate: MoreButtonTapped!
weak var delegate: MapMarkerDelegate?
var spotData: NSDictionary?


@IBAction func didTapInfoButton(_ sender: UIButton) {
delegate?.didTapInfoButton(data: spotData!)
}

class func instanceFromNib() -> UIView {
return UINib(nibName: "MapMarkerWindowView", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView
}

@IBAction func infoButtonPressed(_ sender: Any) {
if(secondDelegate != nil) {
self.secondDelegate.didClickMoreButton(name: nameField.text!)
}
print("Info Button Tapped for \(nameField.text!)")
}


func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "displayLocaleData" {
let destinationVC = segue.destination as! InfoViewController

destinationVC.selectedBarName.text = nameField.text!
}
}
}

这是接收 VC:

import UIKit

class InfoViewController: UIViewController, MoreButtonTapped {




@IBOutlet weak var selectedBarName: UILabel!


@IBOutlet var selectedBarData: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//Assign delegate to self
// MapMarkerWindow.delegate = self
selectedBarName.text = selectedBarName.text
}

func didClickMoreButton(name: String) {
print("Success")
}


}

我没有收到此代码的任何错误。如果我尝试添加 MapMarkerWindow.delegate = self,我会收到错误,因为 UIView 不具备该功能。任何想法或解决方法将不胜感激。

最佳答案

1- 这应该位于包含自定义 nib View 的 vc 内部(假设它是 CustomViewController )

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "displayLocaleData" {
let destinationVC = segue.destination as! InfoViewController
destinationVC.selectedItemName.text = nameField.text!
}
}

2- 当您实例化 MapMarkerWindow 实例时,您需要将委托(delegate)设置为该 CustomViewController

let windoinfo = /// 
windowInfo.delegate = self

3-在此处采用委托(delegate)

class CustomViewController: UIViewController, MoreButtonTapped {

func didClickMoreButton(name: String) {
print("Success")
// here do self.performSegue.....
}
}

关于swift - 创建从 .xib 文件中的 UIButton 到 ViewController 的 Segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693441/

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