我使用MVC模式解析JSON
中的UITableView
值。为此,我创建了一个单独的UITableView
swift类,Model类和UIViewController
类as好。
我可以将JSON值解析为表视图。但问题是我无法使用委托方法将选定的tableView单元格值传递给控制器
我的代码是
UIVIewController:
class ViewController: UIViewController,contactSelectionDelegate {
var contactArray = [Address]()
@IBOutlet weak var userTable: UserTable!
let user = UserTable()
override func viewDidLoad() {
super.viewDidLoad()
user.userdelegate? = self
if Connectivity.isConnectedToInternet() {
print("Yes! Network connection is available")
APIManager.sharedInstance.fetchUserDetails(urlString: FETCH_USER_DETAIL_URL, userCount: ["offset":1]) { connectionResult in
switch connectionResult {
case .success(let data):
do {
self.contactArray = try JSONDecoder().decode([Address].self, from: data)
print(self.contactArray.count)
print(self.contactArray[0].Name)
DispatchQueue.main.async {
print(self.contactArray)
self.userTable.dataSourceArray=self.contactArray
self.userTable.reloadData()
}
}
catch let errorValue {
print(errorValue)
}
case .failure(let error):
print(error)
}
}
}
else{
print("No network connection")
}
}
func selectedUserContact(name: String, email: String, phone: String) {
print("Delegate Called")
let userdetailVC = storyboard?.instantiateViewController(withIdentifier: "UserContactDetailPage") as! UserContactDetailPage
userdetailVC.name = name
userdetailVC.email = email
userdetailVC.phone = phone
self.navigationController?.pushViewController(userdetailVC, animated: true)
} }
UITableView:
protocol contactSelectionDelegate: class{
func selectedUserContact(name: String ,email: String ,phone: String)
}
class UserTable: UITableView ,UITableViewDelegate ,UITableViewDataSource {
var dataSourceArray = [Address]()
weak var userdelegate: contactSelectionDelegate?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.delegate=self
self.dataSource=self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSourceArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UserCell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
if self.dataSourceArray.count>0 {
let myUser = self.dataSourceArray[indexPath.row]
cell.nameLbl.text = myUser.Name
cell.emailLbl.text = myUser.Email
cell.phoneLbl.text = myUser.Phone
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myUser = self.dataSourceArray[indexPath.row]
print(myUser.Name)
print(myUser.Email)
print(myUser.Phone)
userdelegate?.selectedUserContact(name: myUser.Name, email: myUser.Email, phone: myUser.Phone)
}}
当我点击被调用的tableView
单元格didSelectRowAtIndexPath
方法上的表格时,selectedUserContact
未被调用。
答案 0 :(得分:1)
你误解了在这里委派的目的。这个想法是你的表视图只负责绘制一个表,它不应该负责维护它显示的任何数据。这允许您使用模型 - 视图 - 控制器(MVC)范例干净地设计代码。委派允许您的控制器在不破坏MVC的情况下将模型信息传递给视图。
在您的示例中:class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var contactArray = [Address]()
@IBOutlet weak var userTable: UserTable!
override func viewDidLoad() {
super.viewDidLoad()
if Connectivity.isConnectedToInternet() {
print("Yes! Network connection is available")
APIManager.sharedInstance.fetchUserDetails(urlString: FETCH_USER_DETAIL_URL, userCount: ["offset":1]) { connectionResult in
switch connectionResult {
case .success(let data):
do {
self.contactArray = try JSONDecoder().decode([Address].self, from: data)
print(self.contactArray.count)
print(self.contactArray[0].Name)
DispatchQueue.main.async {
print(self.contactArray)
self.userTable.reloadData()
}
}
catch let errorValue {
print(errorValue)
}
case .failure(let error):
print(error)
}
}
}
else{
print("No network connection")
}
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contactArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
let myUser = self.contactArray[indexPath.row]
cell.nameLbl.text = myUser.Name
cell.emailLbl.text = myUser.Email
cell.phoneLbl.text = myUser.Phone
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let myUser = self.contactArray[indexPath.row]
print(myUser.Name)
print(myUser.Email)
print(myUser.Phone)
selectedUserContact(name: myUser.Name, email: myUser.Email, phone: myUser.Phone)
}
// MARK: -
func selectedUserContact(name: String, email: String, phone: String) {
print("Delegate Called")
let userdetailVC = storyboard?.instantiateViewController(withIdentifier: "UserContactDetailPage") as! UserContactDetailPage
userdetailVC.name = name
userdetailVC.email = email
userdetailVC.phone = phone
self.navigationController?.pushViewController(userdetailVC, animated: true)
}
}
是模型,表视图是视图,视图控制器是控制器。因此,您希望控制器符合表格视图的委托/数据源协议,以便它可以正确地将数据提供给它。
ViewController
编辑:我只想补充一点,您需要在故事板中确保将delegate
设置为表格视图的dataSource
和UserTable
。然后,您可以删除您在UITableView
课程中编写的所有代码。如果您根本不需要它,那么您的桌面视图可以很简单UITableViewCell
。我几乎从不创建它的子类,因为你通常可以通过委托和DECLARE @Period INT = 7;
WITH
OrderedRankSets AS (
SELECT
Quotes.StockID
, Quotes.QuoteID
, Quotes.QuoteDay
, PriorQuotes.QuoteDay AS PriorQuoteDay
, PriorQuotes.QuoteClose
, ROW_NUMBER() OVER (PARTITION BY Quotes.StockID, Quotes.QuoteDay ORDER BY PriorQuotes.QuoteDay DESC) AS RowNumber
, COUNT(*) OVER (PARTITION BY Quotes.StockID, Quotes.QuoteDay) AS [RowCount]
FROM
Quotes
JOIN Quotes AS PriorQuotes ON (PriorQuotes.StockID = Quotes.StockID
AND PriorQuotes.QuoteDay <= Quotes.QuoteDay)
)
, RankedQuoteDays AS (
SELECT
OrderedRankSets.*
, CASE WHEN [RowCount] < @Period THEN NULL ELSE RANK() OVER (PARTITION BY StockID, QuoteDay ORDER BY QuoteClose DESC) END AS QuoteRank
FROM
OrderedRankSets
WHERE
RowNumber <= @Period
)
SELECT
RankedQuoteDays.StockID
, RankedQuoteDays.QuoteID
, RankedQuoteDays.QuoteDay
, RankedQuoteDays.QuoteClose
, RankedQuoteDays.QuoteRank
FROM
RankedQuoteDays
WHERE
QuoteDay = PriorQuoteDay
ORDER BY
StockID, QuoteDay
子类来完成所有事情。
答案 1 :(得分:0)
根据这一行,您在故事板中有一个表格视图,并在viewcontroller中获取插座。
@IBOutlet weak var userTable: UserTable!
所以你不需要这样做:
let user = UserTable()
你必须给这样的代表:
userTable.userdelegate? = self
答案 2 :(得分:0)
看起来您正在从故事板中实例化表视图,因此您不会在正确的UserTable实例上设置委托(并且因为委托是nil而永远不会调用委托方法)。
在视图控制器更改
中user.userdelegate? = self
到
userTable.userdelegate? = self
答案 3 :(得分:-1)
对于我来说,它可以正常运行以下方案。请检查一下。
<强>用户表强>
@objc protocol contactSelectionDelegate: class {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
}
weak var userdelegate: contactSelectionDelegate?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
}
ViewController
class ViewController: UIViewController {
}
extension ViewController: contactSelectionDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// YOU CAN GET THE ALL THE STUFFS WHICH IS USER SELECTED IN THE TABLE VIEW
}
}