Search code examples
swiftxcodeuitableviewcustom-cell

Custom Cell with 4 Textfields


I am dealing with a pretty big problem in my current project. I have a page that needs information filled out and sent to users in my Firebase Database. I am not asking about how to send information as of now to these users. I have a view controller that has a table view inserted and constrained properly. Here's an Image:

ViewController

I originally wanted a button in one of the cells. I now have moved on from that and have it in the view above the tableview. When I click that button it appends an array in order to increase the table view cell count.

The cell that I want to populate in the table view needs 4 textfields. I have a custom cell swift file with the following code.

import UIKit

import Firebase

class ConsiderationsCell: UITableViewCell {

let NameTextField: UITextField = {
       let tv = UITextField()
       tv.placeholder = "Name"
       tv.font = UIFont.systemFont(ofSize: 16)
       tv.translatesAutoresizingMaskIntoConstraints = false
       tv.backgroundColor = UIColor.white
       tv.textColor = .black
       return tv
   }()

let FeedTextField: UITextField = {
    let tv = UITextField()
    tv.placeholder = "#"
    tv.font = UIFont.systemFont(ofSize: 16)
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.backgroundColor = UIColor.clear
    tv.textColor = .white
    return tv
}()

let StoryTextField: UITextField = {
    let tv = UITextField()
    tv.placeholder = "#"
    tv.font = UIFont.systemFont(ofSize: 16)
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.backgroundColor = UIColor.clear
    tv.textColor = .white
    return tv
}()

let CompensationTextField: UITextField = {
    let tv = UITextField()
    tv.placeholder = "$"
    tv.font = UIFont.systemFont(ofSize: 16)
    tv.translatesAutoresizingMaskIntoConstraints = false
    tv.backgroundColor = UIColor.clear
    tv.textColor = .white
    return tv
}()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    
    addSubview(NameTextField)
    addSubview(FeedTextField)
    addSubview(StoryTextField)
    addSubview(CompensationTextField)
    
    
    NameTextField.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 20).isActive = true
           NameTextField.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
           NameTextField.widthAnchor.constraint(equalToConstant: 100).isActive = true
           NameTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
    
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

Here is the code for the controller that the cells should appear in:

 import UIKit
 import Firebase

 class ConsiderationsViewController: UIViewController {

var numberOfPeople: [String] = ["1","2"]

var AddPersonCell = "AddPersonCell"

@IBOutlet weak var CompanyImage: UIImageView!

 var database: Database!
    var storage: Storage!
    var selectedImage: UIImage?
    
    var ref:DatabaseReference?
    var databaseHandle:DatabaseHandle = 0
    
    let dbref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set the Firebase reference
        ref = Database.database().reference()
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ConsiderationsViewController.handleSelectCompanyImageView))
         CompanyImage.addGestureRecognizer(tapGesture)
         CompanyImage.isUserInteractionEnabled = true

        self.navigationController!.navigationBar.isTranslucent = false
        
        navigationItem.backBarButtonItem = UIBarButtonItem(
        title: "", style: .plain, target: nil, action: nil)
        
    }

    @objc func handleSelectCompanyImageView() {

        let pickerController = UIImagePickerController()
        pickerController.delegate = self
        pickerController.allowsEditing = true
        present(pickerController, animated: true, completion: nil)
                    }
    
@IBAction func AddPersonTapped(_ sender: Any) {
     insertNewPersonCell()
}

func insertNewPersonCell() {

  }



 }
    
     extension ConsiderationsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
               func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
                   //print("did Finish Picking Media")
                   if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")] as? UIImage{
                       selectedImage = image
                       CompanyImage.image = image
                   }
                   dismiss(animated: true, completion: nil)
               }
    }

  extension ConsiderationsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell, for: indexPath) as! ConsiderationsCell

    return cell
  }
 }

How should I go about constraining these textfields? I would like it to be about the same size as in the image above. I hope I am doing this right. I know StackOverFlow isn't for tutorials but I am having a hard time finding stuff on how to create a custom cell and now that I have code and a better approach, I think it's appropriate to post a question about.

Any help would be greatly appreciated.


Solution

  • class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
        
        @IBOutlet weak var simpleTableView: UITableView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
        
        
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SimpleCell", for: indexPath) as! SimpleCell
            
            if(indexPath.row % 2 == 0 ) {
                
                cell.vi1.backgroundColor = .red
                
            } else {
                
                cell.vi1.backgroundColor = .black
                
            }
            
            return cell
        }
        
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 100
        }
        
    }
    
    
    class SimpleCell: UITableViewCell {
        @IBOutlet weak var vi1: UIView!
        @IBOutlet weak var vi2: UIView!
        override func awakeFromNib() {
            super.awakeFromNib()
            // things done 
        }
    }
    

    Use storyboard connection as @IBOutlets

    Drag & drop UITableView to UIViewController as setting delegate & dataSource

    Select your custom UITableViewCell in storyboard and in Identity Inspector set its cell class to your UITableViewCell class name