Mikl.hart
Mikl.hart

Reputation: 57

Can't pass data from cell to UIView

I want to change value of temperature in UIView (blue square), when I tapping on cell in collection view (date). I am trying to use delegate for it, but i can't do it. I want to change value of selectedIndex and pass this value to UIView in viewModel.weather[selectedIndex]

ViewController with collectionView

protocol WeekCityWeatherViewControllerDelegate {
    func reloadWeatherData()
}

class WeekCityWeatherViewController: UIViewController {
    
    var delegate: WeekCityWeatherViewControllerDelegate?

...

extension WeekCityWeatherViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 7
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dateCell", for: indexPath) as! DateWeekWeatherScreenCell
        
        cell.layer.cornerRadius = 5
        
        if selectedIndex == indexPath.row {
            
            cell.backgroundColor = UIColor.blue
            cell.dateLabel.textColor = UIColor.white
            
        } else {
            cell.backgroundColor = UIColor.white
            cell.dateLabel.textColor = UIColor.black
        }
        
        if let dateInt = viewModel.weather.first?.week.daily[indexPath.item].dt {
            let timeInterval = TimeInterval(dateInt)
            let myNSDate = Date(timeIntervalSince1970: timeInterval)
                
            let dateFormatter2 = DateFormatter()
            dateFormatter2.dateFormat = "dd/MM E"
            dateFormatter2.locale = Locale(identifier: "ru_RU")
            let dateString = dateFormatter2.string(from: myNSDate)
            
            cell.dateLabel.text = dateString
        
        } 
        return cell
    }
}


extension WeekCityWeatherViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: collectionView.frame.width / 5, height: collectionView.frame.height)
    }
}

extension WeekCityWeatherViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        selectedIndex = indexPath.row
        
        self.dateCollectionView.reloadData()
        
        delegate?.reloadWeatherData()
        
    }
}

UIView

class DayView: UIView, WeekCityWeatherViewControllerDelegate {
    
    var viewModel: GeneralViewModel
    var selectedIndex: Int
    var currentIndex: Int
    
    init(frame: CGRect, viewModel: GeneralViewModel, selectedIndex: Int, currentIndex: Int) {
        self.viewModel = viewModel
        self.selectedIndex = selectedIndex
        self.currentIndex = currentIndex
        super.init(frame: frame)
        createSubviews()
        reloadWeatherData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reloadWeatherData() {
        self.reloadInputViews()
    }
    
    private func createSubviews() {
        
        let weekCityWeatherViewController = WeekCityWeatherViewController(viewModel: viewModel, currentIndex: currentIndex)
        
        weekCityWeatherViewController.delegate = self

        let tempLabel = UILabel()
        tempLabel.textColor = .black
        tempLabel.translatesAutoresizingMaskIntoConstraints = false
        tempLabel.font = UIFont(name: "Rubik-Regular", size: 30)
        
        if let maxTemp = viewModel.weather[selectedIndex].week.daily[0].temp.max {
            tempLabel.text = String(format: "%.0f", maxTemp) + " " + "°"
        }
        
        addSubview(tempLabel)
        NSLayoutConstraint.activate([
            tempLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            tempLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10),
            tempLabel.heightAnchor.constraint(equalToConstant: 50),
            tempLabel.widthAnchor.constraint(equalToConstant: 50),
        ])
    }
}

Upvotes: 0

Views: 103

Answers (1)

asilturk
asilturk

Reputation: 218

create a protocol and send the target cell as a parameter in the trigger method. Here is the steps;

// 1. protocol and trigger method 
protocol ItemTableViewCellDelegate: AnyObject {
    func doneButtonTapped(_ cell: ItemTableViewCell)
}

// 2. implement delegate and send the trigger method in your case
class ItemTableViewCell: UITableViewCell {
weak var delegate: ItemTableViewCellDelegate?
//...
}


// MARK: - Implementation
extension ViewController: ItemTableViewCellDelegate {
func doneButtonTapped(_ cell: ItemTableViewCell) {
 // 3. find the index of item you tapped the button, via cell as a parameter
    guard let indexPath = tableView.indexPath(for: cell) else { return }
    var item = MainScreenModel.dummyModel[indexPath.row]
 // 4. reload the cell by indexpath
    tableView.reloadRows(at: [indexPath], with: .automatic)
   }
}

Upvotes: 0

Related Questions