Создание пользовательских ячеек UITableView правильно отображать содержимое (не пусто) - PullRequest
0 голосов
/ 30 апреля 2018

Я работал над созданием приложения для iOS, для которого требуется экран / представление с возможностью прокрутки, в котором есть изображение, затем список, затем изображение, а затем другое изображение (прикреплен снимок экрана с версией Android, которую я сделал)

Верх просмотра

Просмотр с прокруткой

Я попытался использовать следующий код, который дает мне правильное количество ячеек, но все они пустые.

//
//  ServicesTableViewController.swift
//  Contact Australis
//
//  Created by Raghav Khanna on 22/4/18.
//  Copyright © 2018 Australis. All rights reserved.
//

import UIKit
class ServiceViewCell: UITableViewCell {
@IBOutlet weak var IMage: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    IMage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}
class ServiceViewCellList: UITableViewCell {

@IBOutlet weak var somethin_label: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor
    let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor
    let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0)
    let radius: CGFloat = 5
    let border_width:CGFloat = 1.5
    somethin_label.layer.borderColor = color
    somethin_label.layer.borderWidth = border_width
    somethin_label.layer.cornerRadius = radius
    somethin_label.backgroundColor = back_colour_ui
}
var items_maintenance = ["Painting","All Lighting & Globe Replacemt", 
"Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"]
override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
} class ServiceViewCellCleaning: UITableViewCell {

@IBOutlet weak var Title: UIImageView!
override func awakeFromNib() {
    super.awakeFromNib()
   Title.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
}
class ServiceViewCellCleaningList: UITableViewCell {
@IBOutlet weak var other_label: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    let color = UIColor(red: 0/255, green: 105/255, blue: 191/255, alpha: 1.0).cgColor
    let back_colour = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0).cgColor
    let back_colour_ui = UIColor(red: 212/255, green: 242/255, blue: 253/255, alpha: 1.0)
    let radius: CGFloat = 5
    let border_width:CGFloat = 1.5
    other_label.layer.borderColor = color
    other_label.layer.borderWidth = border_width
    other_label.layer.cornerRadius = radius
    other_label.backgroundColor = back_colour_ui
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}
class ServicesTableViewController: UITableViewController {
let basicCellIdentifier = "BasicCell"
var items_maintenance = ["Painting","All Lighting & Globe Replacement", "Carpet & Hard Floor Replacement","Electrical Work & Maintenance","Plumbing Work & Maintenance","Test & Tag Completion","Office Furniture Removal", "Hard Waste Removal", "Window Frosting", "All Other Handy Man & Maintenance Tasks"]
var items_cleaning = ["All Genral Comercial Cleaning","Office Cleaning", "Initial Clean","Spring Clean","Steam Carpet Cleaning","Window Washing","High Pressure Washing", "Waste Removal", "Strip & Seal Hard Floors", "Scrubbing & Buffing Hard Floors"]
let cellSpacingHeight: CGFloat = 5
@IBOutlet var table: UITableView!
func configureTableView() {


    //tableView.rowHeight = UITableViewAutomaticDimension
    //tableView.estimatedRowHeight = 1000.0
    //let rect = CGRect(origin: .zero, size: CGSize(width: 400, height: 400))
    //self.tableView = UITableView(frame: rect, style: UITableViewStyle.plain)
    table.register(ServiceViewCell.self, forCellReuseIdentifier: "maintenance")
     table.register(ServiceViewCellList.self, forCellReuseIdentifier: "customcell")
    table.register(ServiceViewCellCleaning.self, forCellReuseIdentifier: "cleaning")
    table.register(ServiceViewCellCleaningList.self, forCellReuseIdentifier: "cleaning_customcell")

}



/*func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return
}*/




override func viewDidLoad() {
    super.viewDidLoad()
    self.configureTableView()
    table.reloadData()
    table.delegate = self
    table.dataSource = self
    // Uncomment the following line to preserve selection between presentations
    self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 4
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 1
    } else if section == 1 {
      return items_maintenance.count
    } else if section == 2 {
        return 1
    }
    else {
        return items_cleaning.count
    }

}



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let maintenance_title = table.dequeueReusableCell(withIdentifier: "maintenance", for: indexPath) as! ServiceViewCell
    let maintenance_list = table.dequeueReusableCell(withIdentifier: "customcell", for: indexPath) as! ServiceViewCellList
    let cleaning_title = table.dequeueReusableCell(withIdentifier: "cleaning", for: indexPath) as! ServiceViewCellCleaning
    let cleaning_list = table.dequeueReusableCell(withIdentifier: "cleaning_customcell", for: indexPath) as! ServiceViewCellCleaningList

    maintenance_list.somethin_label?.text = self.items_maintenance[indexPath.row]

    maintenance_list.somethin_label?.adjustsFontSizeToFitWidth = false

    maintenance_list.somethin_label?.font = UIFont.systemFont(ofSize: 10.0)

    cleaning_list.other_label?.text = "test"
    cleaning_list.other_label?.adjustsFontSizeToFitWidth = false
    cleaning_list.other_label?.font = UIFont.systemFont(ofSize: 10.0)

    cleaning_title.Title?.image = UIImage(named: "cleaning.png")
    maintenance_title.IMage?.image = UIImage(named: "maintenance.png")
    if indexPath.section  == 0 {
    return maintenance_title
    } else if indexPath.section == 1 {
        return maintenance_list
    } else if indexPath.section == 2 {
        return cleaning_title
    }
else {
        return cleaning_list
    }


    return cleaning_list

}


/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}
*/

/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data source
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}
*/

/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

}
*/


//Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the item to be re-orderable.
    return false
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

Мой раскадровка выглядит следующим образом (это другой вид основной раскадровки с ячейками-прототипами с пользовательскими классами), и я пытаюсь выяснить, почему я продолжаю получать либо «Неожиданно найденный ноль при развертывании дополнительного значение "for" maintenance_list.somethin_label! .text = self.items_maintenance [indexPath.row] "или this (пустые ячейки) при использовании '?' вместо '!'.

Я знаю, почему я не получаю ноль при развертывании ошибки при использовании «?». Но настоящая проблема заключается в том, что я не могу взаимодействовать с представлениями в каждой из ячеек для отображения нужных данных. Я проверил все розетки, и все они верны.

Любая помощь будет принята с благодарностью.

Заранее спасибо.

1 Ответ

0 голосов
/ 30 апреля 2018

Без доступа ко всему проекту сложно сказать, почему он не работает.

Но я думаю, что вы придерживаетесь неправильного подхода, вы должны изучить наличие только двух разделов («Обслуживание», «Очистка»), и тогда каждый элемент «Обслуживание и очистка» будет ячейкой, поэтому ваш источник данных должен возвращать 2 раздела и 10. строки для каждого раздела.

Вам понадобится заголовок раздела, который будет иметь вид изображения, а затем только одну ячейку прототипа, которую вы сможете использовать для любой строки.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...