Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

레시피 리스트UI를 생성해보았습니다. #9

Merged
merged 36 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
6764431
Feat: SearchBar 정의
GeonH0 Jun 19, 2024
10c4c85
Feat: RecipeListView 정의
GeonH0 Jun 19, 2024
69b6ba0
Feat: RecipeListCell 정의
GeonH0 Jun 19, 2024
b740a44
Feat: RecipeListViewController 정의
GeonH0 Jun 19, 2024
68d17da
Fix: ViewModel을 Interactor로 변경해서 ViewController에 적용
GeonH0 Jun 24, 2024
145bd41
Fix: SearchBar final 처리
GeonH0 Jun 24, 2024
db5e2ef
Fix: searchText에 retrun제거
GeonH0 Jun 24, 2024
7a3ba89
Fix: RecipeListView에 final 추가
GeonH0 Jun 24, 2024
db38695
Fix: RecipeListViewCell에 final 추가
GeonH0 Jun 24, 2024
22ee02b
Fix: collectionView를 private 처리
GeonH0 Jun 24, 2024
6edb8bb
Fix: recipelistView를 recipeListView로 네이밍 변경
GeonH0 Jun 24, 2024
2a6372c
Fix: SearchBar 선언 수정
GeonH0 Jun 24, 2024
2be84eb
Fix: 마진 값을 변수로 뺌
GeonH0 Jun 25, 2024
ee35fb9
Fix: imageView 네이밍 변경
GeonH0 Jun 25, 2024
34985f7
Feat: Fonts 객체 정의
GeonH0 Jun 25, 2024
24d0856
Fix: Fonts 객체 적용
GeonH0 Jun 25, 2024
24a71e2
Fix: 이미지 설정코드 setupUI로 이동
GeonH0 Jun 25, 2024
72e9fe8
Feat: loadImage메서드를 extension으로 분리
GeonH0 Jun 25, 2024
cf0c78c
Fix: extension으로 분리된 loadImage 적용
GeonH0 Jun 25, 2024
15f80f0
Fix: RecipeListViewController final 추가
GeonH0 Jun 25, 2024
833b474
Fix: RecipeListViewModelDelegate을 extension으로 확장
GeonH0 Jun 25, 2024
be060c4
Feat: String extenstion에 isBlank 프러퍼티를 추가
GeonH0 Jun 25, 2024
99c274e
Fix: String extenstion에 isBlank 프러퍼티 적용
GeonH0 Jun 25, 2024
c0bd5a0
Fix: didFetchRecipes를 fetchedRecipes로 네이밍 변경
GeonH0 Jun 25, 2024
05b2a58
Merge branch 'main' into feature/feedListView
GeonH0 Jun 25, 2024
52d89ea
Fix: 핸들러에 [weak self] 추가
GeonH0 Jun 25, 2024
1a760ca
Fix: Metric 적용
GeonH0 Jun 26, 2024
3c03347
Fix: 불필요한 return 제거
GeonH0 Jun 29, 2024
7077713
Fix: ViewController에 UICollectionViewDataSource와 UICollectionViewDel…
GeonH0 Jul 1, 2024
c1bc9a0
Fix: RecipeListView에 UICollectionViewDataSource,UICollectionViewDeleg…
GeonH0 Jul 1, 2024
4eb8154
Fix: RecipeListInteractor에서 mapping 기능 제거, result타입으로 전달해서 에러 처리
GeonH0 Jul 1, 2024
e57455d
Fix: Delegate에 didFail제거, 상세화면을 보여주는 메서드 showRecipeDetail정의
GeonH0 Jul 1, 2024
f0115b8
Feat: RecipeListViewDelegate정의,RecipeListInteractorDelegate정의
GeonH0 Jul 1, 2024
d3dcc4e
Fix: Mark 추가
GeonH0 Jul 1, 2024
76fdeba
Feat: 기본 이미지 추가
GeonH0 Jul 1, 2024
e1a3fc2
Fix: RecipeListViewCell에서 기본 이미지 설정
GeonH0 Jul 1, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "EmptyImage.jpg",
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -8,71 +8,56 @@
import Foundation
import RxSwift

protocol RecipeListViewModelDelegate: AnyObject {
func didFetchRecipes(_ recipes: [RecipeListItemViewModel])
func didFail(with error: Error)
protocol RecipeListInteractorDelegate: AnyObject {
func fetchedRecipes(result: Result<[Recipe], Error>)
func showRecipeDetail(ID: Int)
}

protocol InputRecipeListInteractor {
func viewDidLoad()
func fetchNextPage()
func didSelectItem(id: Int) -> RecipeItemViewModel?
func didSelectItem(ID: Int)
func searchRecipes(with query: String)
func resetSearch()
}

protocol OutputRecipeListInteractor {
var recipes: Observable<[RecipeListItemViewModel]> { get }
var error: Observable<Error?> { get }
var recipes: Observable<Result<[Recipe], Error>> { get }
}

class RecipeListInteractor: InputRecipeListInteractor, OutputRecipeListInteractor {

private let disposeBag = DisposeBag()
private let fetchFeedListUseCase: FetchFeedListUseCase
private let searchFeedListUseCase: SearchFeedListUseCase
private let recipeListMapper = RecipeListMapper()
private weak var delegate: RecipeListViewModelDelegate?
private weak var delegate: RecipeListInteractorDelegate?

private var currentPage: Int = 1
private var isFetching = false
private var isSearching = false
private var currentSearchQuery: String?
private var allRecipes: [Recipe] = []

private let recipesSubject = BehaviorSubject<[RecipeListItemViewModel]>(value: [])
private let errorSubject = BehaviorSubject<Error?>(value: nil)
private let recipesSubject = BehaviorSubject<Result<[Recipe], Error>>(value: .success([]))

var recipes: Observable<[RecipeListItemViewModel]> {
var recipes: Observable<Result<[Recipe], Error>> {
return recipesSubject.asObservable()
}

var error: Observable<Error?> {
return errorSubject.asObservable()
}

init(fetchFeedListUseCase: FetchFeedListUseCase, searchFeedListUseCase: SearchFeedListUseCase) {
self.fetchFeedListUseCase = fetchFeedListUseCase
self.searchFeedListUseCase = searchFeedListUseCase
}

func setDelegate(_ delegate: RecipeListViewModelDelegate) {
func setDelegate(_ delegate: RecipeListInteractorDelegate) {
self.delegate = delegate
bindOutputs()
}

private func bindOutputs() {
recipes
.subscribe(onNext: { [weak self] recipes in
self?.delegate?.didFetchRecipes(recipes)
})
.disposed(by: disposeBag)

error
.subscribe(onNext: { [weak self] error in
if let error = error {
self?.delegate?.didFail(with: error)
}
.subscribe(onNext: { [weak self] result in
self?.delegate?.fetchedRecipes(result: result)
})
.disposed(by: disposeBag)
}
Expand All @@ -85,18 +70,15 @@ class RecipeListInteractor: InputRecipeListInteractor, OutputRecipeListInteracto
fetchNextRecipes(nextPage: currentPage)
}

func didSelectItem(id: Int) -> RecipeItemViewModel? {
guard let recipe = allRecipes.first(where: { $0.id == id }) else {
return nil
}
return recipeListMapper.mapToRecipeItemViewModel(from: recipe)
func didSelectItem(ID: Int) {
delegate?.showRecipeDetail(ID: ID)
}

func resetSearch() {
isSearching = false
currentSearchQuery = nil
currentPage = 1
recipesSubject.onNext([])
recipesSubject.onNext(.success([]))
fetchRecipes()
}

Expand All @@ -107,27 +89,33 @@ class RecipeListInteractor: InputRecipeListInteractor, OutputRecipeListInteracto
isSearching = true
currentPage = 1
searchFeedListUseCase.execute(title: title, pageNumber: currentPage)
.subscribe(onSuccess: handleSuccess, onFailure: handleError)
.subscribe { [weak self] result in
self?.handleResult(result)
}
.disposed(by: disposeBag)
}

private func fetchRecipes() {
guard !isFetching else { return }
isFetching = true
fetchFeedListUseCase.execute(pageNumber: currentPage)
.subscribe(onSuccess: handleSuccess, onFailure: handleError)
.subscribe { [weak self] result in
self?.handleResult(result)
}
.disposed(by: disposeBag)
}

private func fetchNextRecipes(nextPage: Int){
private func fetchNextRecipes(nextPage: Int) {
guard !isFetching else { return }
isFetching = true
fetchFeedListUseCase.execute(pageNumber: nextPage)
.subscribe(onSuccess: handleSuccess, onFailure: handleError)
.subscribe { [weak self] result in
self?.handleResult(result)
}
.disposed(by: disposeBag)
}

private func handleSuccess(result: Result<[Recipe], Error>) {
private func handleResult(_ result: Result<[Recipe], Error>) {
isFetching = false
switch result {
case .success(let recipes):
Expand All @@ -139,23 +127,11 @@ class RecipeListInteractor: InputRecipeListInteractor, OutputRecipeListInteracto
} else {
allRecipes.append(contentsOf: recipes)
}
let recipeViewModels = recipeListMapper.mapToRecipeListItemViewModels(from: recipes)
var currentRecipes = try! recipesSubject.value()
if isSearching {
currentRecipes = recipeViewModels
isSearching = false
} else {
currentRecipes.append(contentsOf: recipeViewModels)
}
recipesSubject.onNext(currentRecipes)
currentPage += 1
self.recipesSubject.onNext(.success(allRecipes))
self.currentPage += 1
case .failure(let error):
errorSubject.onNext(error)
recipesSubject.onNext(.failure(error))
}
}

private func handleError(error: Error) {
isFetching = false
errorSubject.onNext(error)
}

}
14 changes: 14 additions & 0 deletions HomeCafeRecipes/HomeCafeRecipes/Extensions/String+Validation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//
// String+Validation.swift
// HomeCafeRecipes
//
// Created by 김건호 on 6/25/24.
//

import Foundation

extension String {
var isBlank: Bool {
self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//
// UIImageViewImageLoading.swift
// HomeCafeRecipes
//
// Created by 김건호 on 6/25/24.
//

import UIKit

extension UIImageView {
func loadImage(from url: URL) {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async {
self.image = UIImage(data: data)
}
}.resume()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//
// RecipeListViewCell.swift
// HomeCafeRecipes
//
// Created by 김건호 on 6/12/24.
//

import UIKit

final class RecipeListViewCell: UICollectionViewCell {

private let recipeThumbnailView = UIImageView()
private let titleLabel = UILabel()

override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}

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

private func setupUI() {
contentView.addSubview(recipeThumbnailView)
contentView.addSubview(titleLabel)

recipeThumbnailView.translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
recipeThumbnailView.topAnchor.constraint(equalTo: topAnchor),
recipeThumbnailView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
recipeThumbnailView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
recipeThumbnailView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.75),

titleLabel.topAnchor.constraint(equalTo: recipeThumbnailView.bottomAnchor, constant: 10),
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10),
titleLabel.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.15)
])

titleLabel.font = Fonts.titleFont
titleLabel.textAlignment = .center

recipeThumbnailView.contentMode = .scaleAspectFill
recipeThumbnailView.clipsToBounds = true
recipeThumbnailView.image = UIImage(named: "EmptyImage")
}

func configure(with viewModel: RecipeListItemViewModel) {
titleLabel.text = viewModel.name
if let imageUrl = viewModel.imageURL {
recipeThumbnailView.loadImage(from: imageUrl)
} else {
recipeThumbnailView.image = UIImage(named: "EmptyImage")
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
//
// RecipeListView.swift
// HomeCafeRecipes
//
// Created by 김건호 on 6/10/24.
//

import UIKit

protocol RecipeListViewDelegate: AnyObject {
func ScrollToBottom()
func didSelectItem(ID: Int)
}

final class RecipeListView: UIView {

private enum Metric {
static let itemSize: CGSize = .init(width: UIScreen.main.bounds.width - 20, height: 200)
static let minimumLineSpacing: CGFloat = 10.0
static let minimumInteritemSpacing: CGFloat = 10.0
}

private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())

private var recipes: [RecipeListItemViewModel] = []
weak var coordinator: RecipeDetailCoordinatorProtocol?
weak var delegate: RecipeListViewDelegate?

override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupLayout()
}

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

private func setupUI() {
backgroundColor = .white
addSubview(collectionView)
collectionView.register(RecipeListViewCell.self, forCellWithReuseIdentifier: "RecipeCell")
configureCollectionView()
}

private func setupLayout() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
])
}

private func configureCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = Metric.itemSize
layout.minimumLineSpacing = Metric.minimumLineSpacing
layout.minimumInteritemSpacing = Metric.minimumInteritemSpacing
collectionView.collectionViewLayout = layout
collectionView.delegate = self
collectionView.dataSource = self
}

func setRecipes(_ recipes: [RecipeListItemViewModel]) {
self.recipes = recipes
collectionView.reloadData()
}
}

// MARK: - UICollectionViewDataSource
extension RecipeListView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recipes.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCell", for: indexPath) as! RecipeListViewCell
let recipeViewModel = recipes[indexPath.item]
cell.configure(with: recipeViewModel)
return cell
}
}

// MARK: - UICollectionViewDelegate
extension RecipeListView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let recipeListItemViewModel = recipes[indexPath.item]
delegate?.didSelectItem(ID: recipeListItemViewModel.id)
}
}

extension RecipeListView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
let height = scrollView.frame.size.height

if offsetY > contentHeight - height {
delegate?.ScrollToBottom()
}
}
}
Loading
Loading