TheSwiftGuy77
TheSwiftGuy77

Reputation: 656

UITableView inside a custom UIView in segmented control does not show the JSON value in custom cell

I have a Segmented control with a UIView in it as shown below:

enter image description here

I have added two custom views inside UIView by the following code:

class NotificationViewController: UIViewController {

@IBOutlet weak var viewContainer: UIView!

//create a variable for view
var views : [UIView]!

override func viewDidLoad() {
    super.viewDidLoad()

    //initialize the view
    views = [UIView]()

    //appened the view inside the views array
    views.append(ImportantNotification().view)
    views.append(GeneralNotificaton().view)

    //start the loop to add the subviews inside the view
    for v in views{
        viewContainer.addSubview(v)
    }

    //bring the default view to the front while we launch it
    viewContainer.bringSubview(toFront: views[0])
}

@IBAction func notificationSegemntsPressed(_ sender: UISegmentedControl) {
    //finally bring the subview inside the segmented view
    self.viewContainer.bringSubview(toFront: views[sender.selectedSegmentIndex])
   }
 }

And it Works!

The sub views with its .xib file are as follows:

enter image description here

I have kept a UI Table view inside the first sub view as shown below:

enter image description here

And, I have made a custom cell for the first subview as shown below:

enter image description here

I loaded the Json data from api and wanted to show it in the table view with the custom cell and the JSON data successfully loads but it doesnot populate in the table view. My code for loading the data in table view is shown below:

import UIKit

class ImportantNotification: UIViewController, UITableViewDelegate,        UITableViewDataSource {

@IBOutlet weak var importantNotificationTableView: UITableView!

var nontificatonData =  [NotificationDataModel]()

override func viewDidLoad() {
    super.viewDidLoad()

    importantNotificationTableView.delegate = self 
    importantNotificationTableView.dataSource = self

    let nib  = UINib(nibName: "TableViewCell", bundle: nil)
    importantNotificationTableView.register(nib, forCellReuseIdentifier: "customCell")

    downloadJSON {

        self.importantNotificationTableView.reloadData()
    }



}

func downloadJSON(completed: @escaping () -> () )  {
    guard let url =   URL(string : "http://www.something.com/notice/get") else {return}
    var request = URLRequest.init(url: url)
    request.httpMethod = "POST"

    request.addValue("cf7ab8c9d4efae82b575eabd6bec76cbb8c6108391e036387f3dd5356a582171519367747000", forHTTPHeaderField: "app_key")

    let postDictonary = "school_id=1"

    //send value directly to server without chaging to json
    request.httpBody = postDictonary.data(using: .utf8)



    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error == nil{
            do{
                self.nontificatonData = try JSONDecoder().decode([NotificationDataModel].self, from: data!)
                print(self.nontificatonData)
                DispatchQueue.main.async {

                    completed()
                }
            }catch{
                print(error)
            }
        }
        }.resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nontificatonData.count
}


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! TableViewCell
    cell.lblTitileNotification.text = nontificatonData[indexPath.row].notice_title
    cell.lblDiscriptionNotificaiton.text = nontificatonData[indexPath.row].notice_desc



    return cell
}


}

My Struct is as follows:

import Foundation

struct NotificationDataModel : Decodable{
let notice_id : String
let notice_title : String
let notice_desc : String
let notice_date : String
let content_name : String
let notice_link : String
let is_important : String
let parent_availability : String
let is_pinned : String
let created_at : String

}

Upvotes: 0

Views: 463

Answers (1)

TheSwiftGuy77
TheSwiftGuy77

Reputation: 656

I'm sorry, but prototype cells are available only in storyboard-based projects. Hopefully you won't have gone too far down the xib approach and can try multiple storyboards instead. If you find them a bit overwhelming, it's OK; they get better – note that you don't have to have one storyboard for all your view controllers. You can have several, either linked in code or using storyboard references.

If you want to stick with xibs, another option is to use registerNib in code. So you design your prototype cells in xibs, then register them in code. Not quite as smooth, but it might suit your needs.

Upvotes: 0

Related Questions