code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,86 @@
+package nextstep.subway.application;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import nextstep.subway.domain.Line;
+import nextstep.subway.domain.LineRepository;
+import nextstep.subway.domain.Station;
+import nextstep.subway.domain.StationRepository;
+import nextstep.subway.dto.LineCreateRequest;
+import nextstep.subway.dto.LineResponse;
+import nextstep.subway.dto.LineUpdateRequest;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional(readOnly = true)
+public class LineService {
+ private final LineRepository lineRepository;
+
+ private final StationRepository stationRepository;
+
+ public LineService(LineRepository lineRepository, StationRepository stationRepository) {
+ this.lineRepository = lineRepository;
+ this.stationRepository = stationRepository;
+ }
+
+ @Transactional
+ public LineResponse saveLine(LineCreateRequest lineCreateRequest) {
+ Line persistLine = lineRepository.save(lineCreateRequest.toLine());
+ addStations(persistLine, lineCreateRequest);
+ return LineResponse.of(persistLine);
+ }
+
+ public LineResponse findLine(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ return LineResponse.of(line.get());
+ }
+
+ public List<LineResponse> findAllLines() {
+ return lineRepository.findAll().stream()
+ .map(LineResponse::of)
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) {
+ Line line = lineRepository.findById(id).get();
+ line.updateLine(lineUpdateRequest);
+ return LineResponse.of(line);
+ }
+
+ @Transactional
+ public void deleteLineById(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ if (line.isPresent()) {
+ line.get().clearRelatedLines();
+ lineRepository.delete(line.get());
+ }
+ }
+
+ private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) {
+ addUpLine(persistLine, lineCreateRequest);
+ addDownLine(persistLine, lineCreateRequest);
+ }
+
+ private void addUpLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasUpStationsId()) {
+ Station station = getStation(lineCreateRequest.getUpStationId());
+ line.addStation(station);
+ }
+ }
+
+ private void addDownLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasDownStationsId()) {
+ Station station = getStation(lineCreateRequest.getDownStationId());
+ line.addStation(station);
+ }
+ }
+
+ private Station getStation(Long stationId) {
+ return stationRepository.findById(stationId)
+ .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์ ํด๋นํ๋ ์ญ์ด ์์ต๋๋ค."));
+ }
+} | Java | id๋ก ๋ผ์ธ์ ์ฐพ์ ์ฐ๊ด๊ด๊ณ๋ฅผ ์ ๊ฑฐํ๋ ๋ก์ง์ ๋ฃ๊ณ ์ ํ๋๋ฐ์,
๋ผ์ธ์ด ์์ ๊ฒฝ์ฐ์๋ง ์ฒ๋ฆฌํ๋ ค๋ค ๋ณด๋ ๋ฐฉ์ด์ฝ๋ ์ฐจ์์ผ๋ก ๋ฃ์์ต๋๋ค.
์ด ๊ฒฝ์ฐ์๋ deleteById ๋ณด๋ค๋ delete ๋ฉ์๋๊ฐ ๋ ์ ํฉํด ๋ณด์ด๋ค์. ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,86 @@
+package nextstep.subway.application;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import nextstep.subway.domain.Line;
+import nextstep.subway.domain.LineRepository;
+import nextstep.subway.domain.Station;
+import nextstep.subway.domain.StationRepository;
+import nextstep.subway.dto.LineCreateRequest;
+import nextstep.subway.dto.LineResponse;
+import nextstep.subway.dto.LineUpdateRequest;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional(readOnly = true)
+public class LineService {
+ private final LineRepository lineRepository;
+
+ private final StationRepository stationRepository;
+
+ public LineService(LineRepository lineRepository, StationRepository stationRepository) {
+ this.lineRepository = lineRepository;
+ this.stationRepository = stationRepository;
+ }
+
+ @Transactional
+ public LineResponse saveLine(LineCreateRequest lineCreateRequest) {
+ Line persistLine = lineRepository.save(lineCreateRequest.toLine());
+ addStations(persistLine, lineCreateRequest);
+ return LineResponse.of(persistLine);
+ }
+
+ public LineResponse findLine(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ return LineResponse.of(line.get());
+ }
+
+ public List<LineResponse> findAllLines() {
+ return lineRepository.findAll().stream()
+ .map(LineResponse::of)
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) {
+ Line line = lineRepository.findById(id).get();
+ line.updateLine(lineUpdateRequest);
+ return LineResponse.of(line);
+ }
+
+ @Transactional
+ public void deleteLineById(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ if (line.isPresent()) {
+ line.get().clearRelatedLines();
+ lineRepository.delete(line.get());
+ }
+ }
+
+ private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) {
+ addUpLine(persistLine, lineCreateRequest);
+ addDownLine(persistLine, lineCreateRequest);
+ }
+
+ private void addUpLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasUpStationsId()) {
+ Station station = getStation(lineCreateRequest.getUpStationId());
+ line.addStation(station);
+ }
+ }
+
+ private void addDownLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasDownStationsId()) {
+ Station station = getStation(lineCreateRequest.getDownStationId());
+ line.addStation(station);
+ }
+ }
+
+ private Station getStation(Long stationId) {
+ return stationRepository.findById(stationId)
+ .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์ ํด๋นํ๋ ์ญ์ด ์์ต๋๋ค."));
+ }
+} | Java | ๋ฆฌํฉํ ๋ง ๋จ๊ณ์์ ๋ฏธ์ฒ ์์ ํ์ง ๋ชปํ ๊ฒ ๊ฐ์ต๋๋ค... |
@@ -0,0 +1,37 @@
+import { Suspense, useState } from "react";
+import { useSearchParams } from "react-router-dom";
+
+import { InputSection } from "./components/InputSection";
+import { ListSection } from "./components/ListSection/ListSection";
+
+export const SearchPage = () => {
+ const [, setSearchParams] = useSearchParams();
+
+ const [keyword, setKeyword] = useState<string>("");
+
+ const handleKeywordChange = (keyword: string) => {
+ setKeyword(keyword);
+ };
+
+ const handleSearch = (keyword: string) => {
+ console.log("๊ฒ์์ด: ", keyword);
+ setSearchParams({ keyword });
+ };
+
+ return (
+ <main>
+ <InputSection
+ keyword={keyword}
+ onKeywordChange={handleKeywordChange}
+ onInputSubmit={handleSearch}
+ />
+ {keyword ? (
+ <Suspense fallback={<p>๊ฒ์์ค...</p>}>
+ <ListSection />
+ </Suspense>
+ ) : (
+ <p>๊ฒ์์ด๋ฅผ ์
๋ ฅํด์ฃผ์ธ์</p>
+ )}
+ </main>
+ );
+}; | Unknown | url์ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ์ด์ฉํด ๊ฒ์์ด ํค์๋๋ฅผ ๊ด๋ฆฌํ๋๋ก ์ค์ ํ ๊ฒ์, url์ ์ ๋ฌํ๋ฉฐ ๊ฒ์ ๊ฒฐ๊ณผ๋ ํจ๊ป ์ ๋ฌํ ์ ์๋๋ก ํ๊ธฐ ์ํจ์ด์์. ๊ทธ๋ฐ๋ฐ ํ์ฌ๋ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ๊ฒ์์ด์ ๊ธฐ๋ณธ๊ฐ์ผ๋ก ๋ด๋ ค๋ฐ์ง ๋ชปํ๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ด์.
TODO: ์์นํ๋ผ๋ฏธํฐ ๊ฐ์ ํค์๋ ์ด๊ธฐ๊ฐ์ผ๋ก ์ค์
```suggestion
const [searchParams, setSearchParams] = useSearchParams();
const [keyword, setKeyword] = useState<string>(searchParams.get("keyword") || "");
``` |
@@ -0,0 +1,30 @@
+import { useLazyLoadQuery } from "react-relay";
+import { useSearchParams } from "react-router-dom";
+
+import { graphql } from "relay-runtime";
+
+import { ListSectionRepositorySearchQuery } from "./__generated__/ListSectionRepositorySearchQuery.graphql";
+
+import { RepositoryPagination } from "./RepositoryPagination";
+
+export const ListSection = () => {
+ const [searchParams] = useSearchParams();
+ const keyword = searchParams.get("keyword") || "";
+
+ const data = useLazyLoadQuery<ListSectionRepositorySearchQuery>(
+ graphql`
+ query ListSectionRepositorySearchQuery($keyword: String!) {
+ ...RepositoryPagination @arguments(keyword: $keyword)
+ }
+ `,
+ {
+ keyword,
+ }
+ );
+
+ return (
+ <ul>
+ <RepositoryPagination data={data} />
+ </ul>
+ );
+}; | Unknown | TODO: List Section ๋ด์์ ํค์๋๋ฅผ ์ง์ ๊ฐ์ ธ์ค์ง ๋ง๊ณ , Search Page์์ props๋ก ํค์๋๋ฅผ ์ฃผ์
๋ฐ๋๋ก ๋ณ๊ฒฝ |
@@ -0,0 +1,87 @@
+import { graphql, useFragment, useMutation } from "react-relay";
+
+import { RepositoryItem_repository$key } from "./__generated__/RepositoryItem_repository.graphql";
+import { RepositoryItemAddStarMutation } from "./__generated__/RepositoryItemAddStarMutation.graphql";
+import { RepositoryItemRemoveStarMutation } from "./__generated__/RepositoryItemRemoveStarMutation.graphql";
+
+import { StarButton } from "./StarButton";
+
+type RepositoryItemProps = {
+ repository: RepositoryItem_repository$key;
+};
+
+const RepositoryStarAddMutation = graphql`
+ mutation RepositoryItemAddStarMutation($id: ID!) {
+ addStar(input: { starrableId: $id }) {
+ starrable {
+ id
+ viewerHasStarred
+ }
+ }
+ }
+`;
+
+const RepositoryStarRemoveMutation = graphql`
+ mutation RepositoryItemRemoveStarMutation($id: ID!) {
+ removeStar(input: { starrableId: $id }) {
+ starrable {
+ id
+ viewerHasStarred
+ }
+ }
+ }
+`;
+
+export const RepositoryItem = (props: RepositoryItemProps) => {
+ const payload = useFragment(
+ graphql`
+ fragment RepositoryItem_repository on Repository {
+ id
+ name
+ url
+ description
+ stargazerCount
+ viewerHasStarred
+ }
+ `,
+ props.repository
+ );
+
+ const [add, isAdding] = useMutation<RepositoryItemAddStarMutation>(
+ RepositoryStarAddMutation
+ );
+
+ const [remove, isRemoving] = useMutation<RepositoryItemRemoveStarMutation>(
+ RepositoryStarRemoveMutation
+ );
+
+ if (!payload) {
+ return null;
+ }
+
+ const { id, url, name, description, stargazerCount, viewerHasStarred } =
+ payload;
+
+ const isLoading = isAdding || isRemoving;
+
+ return (
+ <li>
+ <a href={url} target="_blank" rel="noreferrer">
+ {name}
+ </a>
+ <p>{description}</p>
+ <p>โญ๏ธ {stargazerCount}</p>
+
+ {isLoading ? (
+ <div>...</div>
+ ) : (
+ <StarButton
+ repositoryId={id}
+ isStarred={viewerHasStarred}
+ onAddStar={() => add({ variables: { id } })}
+ onRemoveStar={() => remove({ variables: { id } })}
+ />
+ )}
+ </li>
+ );
+}; | Unknown | TODO: add, remove์ ๋ํ ๋ณ์๊ฐ์ StarButton ๋ด์์ ๋๊ฒจ๋ฐ๋๋ก ๋ณ๊ฒฝ |
@@ -1 +1,30 @@
-# java-lotto ๊ฒ์
+# java-Lotto ๊ฒ์
+
+# ๊ตฌํ ๊ธฐ๋ฅ ๋ชฉ๋ก
+
+- [x] ๊ตฌ์
๊ธ์ก ์
๋ ฅ๋ฐ๊ธฐ
+ - [x] 1000์ ๋ฏธ๋ง ์
๋ ฅ ์ ์ฒ๋ฆฌ
+ - [x] 1000์ ๋ฐฐ์ ์๋ ๊ฐ ์
๋ ฅ ์ ์ฒ๋ฆฌ
+ - [x] ์ซ์๊ฐ ์๋ ๊ฐ (๋ฌธ์์ด)
+ - [x] ์ ์๊ฐ ์ฒ๋ฆฌ
+ - [x] ๊ณต๋ฐฑ ์ฒ๋ฆฌ
+- [x] ๊ตฌ๋งค ๊ฐ์ ๊ตฌํ๊ธฐ
+- [x] ๋๋ค ๋ก๋๋ฒํธ ๊ตฌ๋งค ๊ฐ์๋งํผ ๋ง๋ค๊ธฐ
+ - [x] defaultNumberSet 1๋ฒ๋ง ์์ฑ๋๋๋ก ๋ณ๊ฒฝ
+ - [x] RandomLottoTest ์์ ๋ฆฌํฉํ ๋ง
+ - [x] PurchaseCount์ 1000 ์ ๊ทผ
+- [x] ์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ ์
๋ ฅ๋ฐ๊ธฐ
+ - [x] WinningNumbers ๋ฉค๋ฒ๋ณ์ ArrayList ํด๋์ค ํ์ธ
+ - [x] ์ซ์ ๊ฐ์ 6๊ฐ ํ์ธ
+ - [x] ์ซ์๊ฐ ์๋ ๊ฐ ํฌํจ
+ - [x] ๋ฒ์ (1~45) ํ์ธ
+ - [x] ๊ณต๋ฐฑ ์ฒ๋ฆฌ
+- [x] ๋ณด๋์ค ๋ณผ ์
๋ ฅ๋ฐ๊ธฐ
+- [x] ๋น์ฒจ ํต๊ณ
+ - [x] ๋น์ฒจ ์กฐ๊ฑด์ enum ์ฒ๋ฆฌ
+ - [x] ์ผ์น ๊ฐ์ ์ฐพ๊ธฐ
+ - [x] 5๊ฐ ์ผ์น ์ ๋ณด๋์ค ๋ณผ ์ผ์น ์ฌ๋ถ ํ์ธ
+ - [x] ๋ก๋ ๋น์ฒจ ๊ฐ์ ๊ตฌํ๊ธฐ
+ - [x] ๋น์ฒจ๊ฐ์ ํฉ ๊ตฌํ๊ธฐ
+ - [x] ์์ต๋ฅ ๊ตฌํ๊ธฐ
+ - [x] ๊ฒฐ๊ณผ ์ถ๋ ฅ
\ No newline at end of file | Unknown | ๊ตฌํ ๊ธฐ๋ฅ ๋ชฉ๋ก ์์ฑ ๐ |
@@ -10,6 +10,13 @@ repositories {
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
testImplementation('org.assertj:assertj-core:3.15.0')
+
+ compileOnly 'org.projectlombok:lombok:1.18.20'
+ annotationProcessor 'org.projectlombok:lombok:1.18.20'
+
+ testCompileOnly 'org.projectlombok:lombok:1.18.20'
+ testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
+
}
test { | Unknown | ๋กฌ๋ณต ํ๋ฌ๊ทธ์ธ์ ํ์ฉํ์
จ๋ค์! |
@@ -0,0 +1,24 @@
+package lotto.controller;
+
+import lotto.domain.dto.LottoResult;
+import lotto.domain.dto.PurchaseInput;
+import lotto.domain.dto.PurchaseResult;
+import lotto.domain.dto.WinningLottoInput;
+import lotto.service.LottoService;
+
+public class LottoController {
+
+ private final LottoService lottoService;
+
+ public LottoController() {
+ this.lottoService = new LottoService();
+ }
+
+ public PurchaseResult purchase(PurchaseInput purchaseInput) throws IllegalArgumentException {
+ return lottoService.purchase(purchaseInput);
+ }
+
+ public LottoResult calculateResult(PurchaseResult purchaseResult, WinningLottoInput winningLottoInput) throws IllegalArgumentException {
+ return lottoService.calculateResult(purchaseResult, winningLottoInput);
+ }
+} | Java | MVC ํจํด์ ์ด์ฉํด ๋ฌธ์ ๋ฅผ ํ๋ ค๊ณ ์๋ํ์
จ๋ค์!
๋ค๋ง Model - View - Controller ์ญํ ๋ถ๋ฆฌ๊ฐ ๋ช
ํํ๊ฒ ๋์ด์์ง ์์
ํ์ฌ Controller๊ฐ View๋ฅผ ์ง์ ํ์ฉํ๋ ๋ฐฉ์์ผ๋ก ์ฝ๋ ๊ตฌํ์ด ๋์ด์๋๋ฐ์.
๊ฐ์์ ์ญํ ๊ณผ ์ฑ
์์ ๋ฌด์์ด๊ณ , ์ด๋ฅผ ์ด๋ป๊ฒ ๋
๋ฆฝ์ ์ผ๋ก ๋ถ๋ฆฌํด๋ผ ์ ์์ ์ง, ๋ ์ ๊ทธ๋ฌํ์ฌ์ผ ํ๋์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข๊ฒ ์ต๋๋ค. ํ์ฌ๋ `LottoController.start()` ๋ `LottoApplication`์ main๊ณผ ๊ฐ์ ์ญํ ๋ก ๋ณด์ด๋ค์. |
@@ -0,0 +1,31 @@
+package lotto.view;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Scanner;
+import java.util.stream.Collectors;
+
+public class ConsoleInputView implements InputView {
+
+ private static final String LOTTO_NUMBERS_INPUT_DELIMITER = ",";
+
+ private final Scanner scanner = new Scanner(System.in);
+
+ public Integer getPurchaseCost() throws NumberFormatException {
+ String input = scanner.nextLine().trim();
+ return Integer.parseInt(input);
+ }
+
+ public List<Integer> getWinningLottoNumbers() throws NumberFormatException {
+ String input = scanner.nextLine();
+ return Arrays.stream(input.split(LOTTO_NUMBERS_INPUT_DELIMITER))
+ .map(String::trim)
+ .map(Integer::new)
+ .collect(Collectors.toList());
+ }
+
+ public Integer getWinningLottoBonus() throws NumberFormatException {
+ String input = scanner.nextLine().trim();
+ return Integer.parseInt(input);
+ }
+} | Java | ๊ณผํ(๋ถํ์ํ) ๋ฉ์๋ ํฌ์ฅ์
๋๋ค. |
@@ -0,0 +1,86 @@
+package lotto.view;
+
+import lotto.domain.*;
+import lotto.domain.dto.LottoResult;
+
+public class ConsoleOutputView implements OutputView {
+
+ private static final String ERROR_HEADER = "[ERROR] ";
+
+ private void print(String contents) {
+ System.out.println(contents);
+ }
+
+ public void printLottoCount(PurchaseCount purchaseCount) {
+ int count = purchaseCount.getPurchaseCount();
+ print(count + "๊ฐ๋ฅผ ๊ตฌ๋งคํ์ต๋๋ค.");
+ }
+
+ public void printLottoSet(LottoSet lottoSet) {
+ for (Lotto lotto : lottoSet.getLottoSet()) {
+ printLotto(lotto);
+ }
+ }
+
+ private void printLotto(Lotto lotto) {
+ String result = "[";
+ for (LottoNumber lottoNumber : lotto.getLottoNumbers()) {
+ result += lottoNumber.getLottoNumber() + ", ";
+ }
+ result = removeCommaAtTheEnd(result) + "]";
+
+ print(result);
+ }
+
+ private String removeCommaAtTheEnd(String str) {
+ return str.substring(0, str.length() - 2);
+ }
+
+ public void askPurchaseCost() {
+ print("๊ตฌ์
๊ธ์ก์ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+
+ public void askWinningLottoNumbers() {
+ print("์ง๋ ์ฃผ ๋น์ฒจ ๋ฒํธ๋ฅผ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+
+ public void askWinningLottoBonus() {
+ print("๋ณด๋์ค ๋ณผ์ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+
+ public void printLottoStatistic(LottoResult lottoStatistics) {
+ String result = "๋น์ฒจ ํต๊ณ\n---------\n" +
+ generatePrizeResultMessage(Prize.FIFTH, lottoStatistics.getPrizeCount().getFifth()) +
+ generatePrizeResultMessage(Prize.FOURTH, lottoStatistics.getPrizeCount().getFourth()) +
+ generatePrizeResultMessage(Prize.THIRD, lottoStatistics.getPrizeCount().getThird()) +
+ generatePrizeResultMessage(Prize.SECOND, lottoStatistics.getPrizeCount().getSecond()) +
+ generatePrizeResultMessage(Prize.FIRST, lottoStatistics.getPrizeCount().getFirst()) +
+ generateProfitRateMessage(lottoStatistics.getProfitRate());
+ print(result);
+ }
+
+ private String generatePrizeResultMessage(Prize prize, int prizeCount) {
+ return generatePrizeResultMessage(prize) + prizeCount + "๊ฐ\n";
+ }
+
+ private String generatePrizeResultMessage(Prize prize) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(prize.getMatchNumbersCount())
+ .append("๊ฐ ์ผ์น");
+ if (prize.isBonus()) {
+ sb.append(", ๋ณด๋์ค ๋ณผ ์ผ์น ");
+ }
+ sb.append("(")
+ .append(prize.getPrizeMoney())
+ .append("์)- ");
+ return sb.toString();
+ }
+
+ private String generateProfitRateMessage(double profitRate) {
+ return "์ด ์์ต๋ฅ ์ " + profitRate + "์
๋๋ค.";
+ }
+
+ public void printException(String message) {
+ print(ERROR_HEADER + message);
+ }
+} | Java | line 9 to 13
๋๋ฌด ๋ช
ํํ ๊ฐ๋ค์ด ๊ณผํ๊ฒ ์์๋ก ๋ง๋ค์ด์ก์ต๋๋ค.
๋ชจ๋ literal value๊ฐ ๋์ ๊ฒ์ ์๋๋๋ค. ^^; |
@@ -0,0 +1,33 @@
+package lotto.service;
+
+import lotto.domain.*;
+import lotto.domain.dto.LottoResult;
+import lotto.domain.dto.PurchaseInput;
+import lotto.domain.dto.PurchaseResult;
+import lotto.domain.dto.WinningLottoInput;
+
+public class LottoService {
+
+ public PurchaseResult purchase(PurchaseInput purchaseInput) throws IllegalArgumentException {
+ PurchaseCount purchaseCount = new PurchaseCount(purchaseInput.getPrice());
+ LottoSet lottoSet = new LottoSet(purchaseCount);
+
+ return PurchaseResult.builder()
+ .purchaseCount(purchaseCount)
+ .lottoSet(lottoSet)
+ .build();
+ }
+
+ public LottoResult calculateResult(PurchaseResult purchaseResult, WinningLottoInput winningLottoInput) throws IllegalArgumentException {
+ LottoMatcher lottoMatcher = new LottoMatcher(
+ new WinningLotto(winningLottoInput), purchaseResult.getLottoSet()
+ );
+ PrizeCount prizeCount = lottoMatcher.countPrizes();
+ LottoStatistics lottoStatistics = new LottoStatistics(prizeCount, purchaseResult.getPurchaseCount());
+
+ return LottoResult.builder()
+ .prizeCount(prizeCount)
+ .profitRate(lottoStatistics.calculateProfitRate())
+ .build();
+ }
+} | Java | PurchaseCount ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ์ด ์์ ์ ์ ํจ์ฑ ๊ฒ์ฆ์ด ํด๋น ๊ฐ์ฒด ์์ฑ์์์ ์งํ๋๋๋ฐ์,
์ปจํธ๋กค๋ฌ ๋ ์ด์ด์์ ์ฌ์ฉ์์ ์
๋ ฅ ๊ฐ์ ์ ํจ์ฑ์ ๋จผ์ ๊ฒ์ฆํ ์ ์์ง ์์๊น์?
๊ณ ๋ฏผํด๋ณผ ๊ฑฐ๋ฆฌ: ์ ํจ์ฑ ๊ฒ์ฆ์ ์ด๋ค ๋ ์ด์ด์์ ์งํ๋์ด์ผํ ๊น? |
@@ -0,0 +1,19 @@
+package lotto.exception;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import lotto.domain.Lotto;
+
+@RequiredArgsConstructor
+public enum ExceptionMessage {
+
+ NON_NUMBER_INPUT("์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์."),
+ LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY("๊ตฌ์
๊ธ์ก์ " + Lotto.PRICE + " ์ด์์ ๊ฐ์ ์
๋ ฅํด์ฃผ์ธ์."),
+ NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY("๊ตฌ์
๊ธ์ก์ " + Lotto.PRICE + "์ ๋ฐฐ์๋ก ์
๋ ฅํด์ฃผ์ธ์."),
+ INVALID_LENGTH_INPUT_FOR_LOTTO("๋ก๋ ๋ฒํธ๋ 6๊ฐ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์"),
+ DUPLICATE_LOTTO_NUMBER_INPUT_FOR_LOTTO("๋ก๋ ๋ฒํธ๋ ์ค๋ณต๋์ง ์๋ 6๊ฐ์ ์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์"),
+ OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER("๋ก๋ ๋ฒํธ๋ 1 ์ด์ 45 ์ดํ์ ๊ฐ์ ์
๋ ฅํด์ฃผ์ธ์.");
+
+ @Getter
+ private final String message;
+} | Java | ์์ธ ๋ฉ์์ง๋ฅผ ๋ณ๋๋ก ๋ถ๋ฆฌํด์ ํ ๊ณณ์์ ๊ด๋ฆฌํ๊ณ ์๋ค์!
ํ์ฌ๋ IllegalArgumentException๋ง์ ์ฌ์ฉํ๊ณ ๋ฉ์์ง๋ก ํน์ ์์ธ์ ๋ํด์ ์ฒ๋ฆฌํ๊ณ ์๋๋ฐ์,
๊ตฌ์ฒด์ ์ธ CustomException์ ๋ง๋ค๊ณ ์ํฉ์ ๋ฐ๋ผ ์ด๋ฅผ ๋์ ธ ํด๋น Exception์ ํ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์๊ฐํด๋ณผ ์ ์์ต๋๋ค. |
@@ -0,0 +1,53 @@
+package lotto.domain;
+
+import lombok.Getter;
+
+import java.util.Objects;
+
+import static lotto.exception.ExceptionMessage.OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER;
+
+public class LottoNumber {
+
+ public static final int LOWER_BOUND = 1;
+ public static final int UPPER_BOUND = 45;
+
+ @Getter
+ private final int lottoNumber;
+
+ public LottoNumber(int lottoNumber) throws IllegalArgumentException {
+ validate(lottoNumber);
+
+ this.lottoNumber = lottoNumber;
+ }
+
+ private void validate(int lottoNumber) throws IllegalArgumentException {
+ if (isOutOfBound(lottoNumber)) {
+ throw new IllegalArgumentException(OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER.getMessage());
+ }
+ }
+
+ private boolean isOutOfBound(int lottoNumber) {
+ return lottoNumber < LOWER_BOUND || lottoNumber > UPPER_BOUND;
+ }
+
+ public boolean isGreaterThan(LottoNumber winningNumber) {
+ return this.getLottoNumber() > winningNumber.getLottoNumber();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LottoNumber that = (LottoNumber) o;
+ return lottoNumber == that.lottoNumber;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(lottoNumber);
+ }
+} | Java | `isInteger` ๋ ์ง๋
ํ๋ฉด ์ ์์ธ๊ฐ? ๋ ํ๋จ๋ฌธ์
๋๋ค.
๋ค๋ง ๋ด์ฉ์ ๋ณด๋ 0~9๊น์ง ์ซ์ ์ฆ ์์ด ์๋ ์ ์์ธ์ง๋ฅผ ์ ๊ทํํ์์ ์ด์ฉํด ํ๋จํ๊ณ ์๋ค์.
isNonNegativeInteger ์ ๋๋ก ๋ ์ ํํ๊ฒ ํํํด๋ณด๋ฉด ์ด๋จ๊น์?
```suggestion
if (!isNonNegativeInteger(input)) {
``` |
@@ -0,0 +1,35 @@
+package lotto.domain;
+
+import lombok.Builder;
+import lombok.Getter;
+
+import static lotto.exception.ExceptionMessage.LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY;
+import static lotto.exception.ExceptionMessage.NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY;
+
+public class PurchaseCount {
+
+ private static final int MINIMUM_INPUT = 1000;
+
+ @Getter
+ private final Integer purchaseCount;
+
+ @Builder
+ public PurchaseCount(int purchasePrice) {
+ validate(purchasePrice);
+
+ this.purchaseCount = purchasePrice / Lotto.PRICE;
+ }
+
+ private void validate(int purchasePrice) {
+ if (purchasePrice < MINIMUM_INPUT) {
+ throw new IllegalArgumentException(LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage());
+ }
+ if (notMultipleOfLottoPrice(purchasePrice)) {
+ throw new IllegalArgumentException(NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage());
+ }
+ }
+
+ private boolean notMultipleOfLottoPrice(int input) {
+ return input % Lotto.PRICE != 0;
+ }
+} | Java | `isInteger` ๋ ์ง๋
ํ๋ฉด ์ ์์ธ๊ฐ? ๋ ํ๋จ๋ฌธ์
๋๋ค.
๋ค๋ง ๋ด์ฉ์ ๋ณด๋ 0~9๊น์ง ์ซ์ ์ฆ ์์ด ์๋ ์ ์์ธ์ง๋ฅผ ์ ๊ทํํ์์ ์ด์ฉํด ํ๋จํ๊ณ ์๋ค์.
isNonNegativeInteger ์ ๋๋ก ๋ ์ ํํ๊ฒ ํํํด๋ณด๋ฉด ์ด๋จ๊น์?
```suggestion
if (!isNonNegativeInteger(input)) {
``` |
@@ -0,0 +1,35 @@
+package lotto.domain;
+
+import lombok.Builder;
+import lombok.Getter;
+
+import static lotto.exception.ExceptionMessage.LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY;
+import static lotto.exception.ExceptionMessage.NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY;
+
+public class PurchaseCount {
+
+ private static final int MINIMUM_INPUT = 1000;
+
+ @Getter
+ private final Integer purchaseCount;
+
+ @Builder
+ public PurchaseCount(int purchasePrice) {
+ validate(purchasePrice);
+
+ this.purchaseCount = purchasePrice / Lotto.PRICE;
+ }
+
+ private void validate(int purchasePrice) {
+ if (purchasePrice < MINIMUM_INPUT) {
+ throw new IllegalArgumentException(LESS_THAN_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage());
+ }
+ if (notMultipleOfLottoPrice(purchasePrice)) {
+ throw new IllegalArgumentException(NON_MULTIPLE_OF_LOTTO_PRICE_INPUT_FOR_PURCHASE_MONEY.getMessage());
+ }
+ }
+
+ private boolean notMultipleOfLottoPrice(int input) {
+ return input % Lotto.PRICE != 0;
+ }
+} | Java | `notMatchesCondition` ํํ์ด ๋ชจํธํ๊ณ ๋ ๊ฐ์ง ์๋ก ๋ค๋ฅธ ์ผ์ ํ๊ณ ์์ต๋๋ค.
1. ์
๋ ฅ์ด ๋ก๋๋ฅผ ๊ตฌ๋งคํ ์ ์๋ ์ต์ ๊ฐ(1000)๋ฏธ๋ง์ธ์ง ๊ฒ์ฆ
2. ์ ํํ ํฐ์ผ ๊ฐ๊ฒฉ์ ๋ฐฐ์์ธ์ง ๊ฒ์ฆ
1์ ์ํฉ์ 2์ ๋ถ๋ถ์งํฉ์ผ๋ก ์๊ฐํ์ฌ ๊ตฌํํ์ ๊ฒ์ผ๋ก ์ถ์ธก๋๋๋ฐ,
์ฌ์ฉ์์๊ฒ ์คํจ์ ๋ํ ๋ ์ ํํ ์๋ฌ๋ฅผ ๊ตฌ๋ถํ์ฌ ๋
ธ์ถํ๋ ๊ฒ์ด ์ข์ง ์์๊น์? |
@@ -0,0 +1,17 @@
+package lotto.domain;
+
+import lombok.Builder;
+import lombok.Getter;
+import lotto.domain.dto.WinningLottoInput;
+
+public class WinningLotto extends Lotto {
+
+ @Getter
+ private final LottoNumber bonusNumber;
+
+ @Builder
+ public WinningLotto(WinningLottoInput winningLottoInput) throws IllegalArgumentException {
+ super(winningLottoInput.getNumbers());
+ this.bonusNumber = new LottoNumber(winningLottoInput.getBonus());
+ }
+} | Java | ์ฌ์ฉ์ ์
๋ ฅ(InputView)์ ๋ํ ํ์ฑ๊ณผ ๊ฒ์ฆ์ด ์๋น์ค ๋ ์ด์ด๋ฅผ ํต๊ณผํด ๋๋ฉ์ธ ๋ชจ๋ธ๊น์ง ์นจํฌํ์ต๋๋ค.
์ด๋ฅผ ๋ด๋นํ๋ ์์ญ์ธ ์ปจํธ๋กค๋ฌ ๋ ์ด์ด์์ ์ ์์
์ ๋ชจ๋ ๋ง๋ฌด๋ฆฌ์ง์ด์ผํฉ๋๋ค.
๊ฐ๊ธ์ ๋๋ฉ์ธ ๋ชจ๋ธ์ ์ฌ์ฉ์ ์
๋ ฅ ๋ฐฉ์๊ณผ ๋
๋ฆฝ์ ์ด์ด์ผํฉ๋๋ค.
์ด๋ค ๋ทฐ๋ฅผ ํตํด ์ ๊ทผํ๋ ๋๋ฉ์ธ์ ๊ทธ ์์ฒด๋ก ๋ฌธ์ ์์ญ๋ง์ ํํํ๊ณ ํด๊ฒฐํ๋ ๋ ์ด์ด์ด์ด์ผํฉ๋๋ค. |
@@ -0,0 +1,53 @@
+package lotto.domain;
+
+import lombok.Getter;
+
+import java.util.Objects;
+
+import static lotto.exception.ExceptionMessage.OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER;
+
+public class LottoNumber {
+
+ public static final int LOWER_BOUND = 1;
+ public static final int UPPER_BOUND = 45;
+
+ @Getter
+ private final int lottoNumber;
+
+ public LottoNumber(int lottoNumber) throws IllegalArgumentException {
+ validate(lottoNumber);
+
+ this.lottoNumber = lottoNumber;
+ }
+
+ private void validate(int lottoNumber) throws IllegalArgumentException {
+ if (isOutOfBound(lottoNumber)) {
+ throw new IllegalArgumentException(OUT_OF_BOUND_INPUT_FOR_LOTTO_NUMBER.getMessage());
+ }
+ }
+
+ private boolean isOutOfBound(int lottoNumber) {
+ return lottoNumber < LOWER_BOUND || lottoNumber > UPPER_BOUND;
+ }
+
+ public boolean isGreaterThan(LottoNumber winningNumber) {
+ return this.getLottoNumber() > winningNumber.getLottoNumber();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LottoNumber that = (LottoNumber) o;
+ return lottoNumber == that.lottoNumber;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(lottoNumber);
+ }
+} | Java | LottoNumber๋ฅผ ์์ฑํ ๋ String์ผ๋ก ์์ฑํ ํ์๊ฐ ์์๊น์?
String type์ผ๋ก ๋ฐ๋ค๋ณด๋ ํ๋ณํ๊น์ง ์ฑ
์์ ธ์ผํ๋ ์ํฉ์ด ๋์๋ค์. |
@@ -0,0 +1,17 @@
+package lotto.domain;
+
+import lombok.Builder;
+import lombok.Getter;
+import lotto.domain.dto.WinningLottoInput;
+
+public class WinningLotto extends Lotto {
+
+ @Getter
+ private final LottoNumber bonusNumber;
+
+ @Builder
+ public WinningLotto(WinningLottoInput winningLottoInput) throws IllegalArgumentException {
+ super(winningLottoInput.getNumbers());
+ this.bonusNumber = new LottoNumber(winningLottoInput.getBonus());
+ }
+} | Java | ๋ฐ๋ณต๋ฌธ๊ณผ ์กฐ๊ฑด๋ฌธ์ ์ค์ฒฉํด์ ๋ก์ง์ด ๋ณต์กํ๋ค์.
๋ ๋์ ๋ฐฉ์์ผ๋ก ๋ฆฌํฉํ ๋ง์ ํด์ผ๊ฒ ์ฃ ? |
@@ -0,0 +1,55 @@
+package lotto.domain;
+
+import lombok.Getter;
+
+@Getter
+public enum Prize {
+
+ FIRST(6, false, 2000000000),
+ SECOND(5, true, 30000000),
+ THIRD(5, false, 1500000),
+ FOURTH(4, false, 50000),
+ FIFTH(3, false, 5000),
+ LOSE(2, false, 0);
+
+ private final int matchNumbersCount;
+ private final boolean isBonus;
+ private final long prizeMoney;
+
+ Prize(int matchNumbersCount, boolean isBonus, long prizeMoney) {
+ this.matchNumbersCount = matchNumbersCount;
+ this.isBonus = isBonus;
+ this.prizeMoney = prizeMoney;
+ }
+
+ public static Prize getMatchPrize(int matchNumbersCount, boolean isBonus) {
+ if (matchNumbersCount <= LOSE.matchNumbersCount) {
+ return LOSE;
+ }
+ if (matchNumbersCount == FIFTH.matchNumbersCount) {
+ return FIFTH;
+ }
+ if (matchNumbersCount == FOURTH.matchNumbersCount) {
+ return FOURTH;
+ }
+ if (matchNumbersCount == FIRST.matchNumbersCount) {
+ return FIRST;
+ }
+ return dissolveSecondOrThird(isBonus);
+ }
+
+ private static Prize dissolveSecondOrThird(boolean isBonus) {
+ if (isBonus) {
+ return Prize.SECOND;
+ }
+ return Prize.THIRD;
+ }
+
+ public static long sumOfPrizeMoney(PrizeCount prizeCount) {
+ return prizeCount.getFirst() * FIRST.prizeMoney
+ + prizeCount.getSecond() * SECOND.prizeMoney
+ + prizeCount.getThird() * THIRD.prizeMoney
+ + prizeCount.getFourth() * FOURTH.prizeMoney
+ + prizeCount.getFifth() * FIFTH.prizeMoney;
+ }
+} | Java | Enum ํ์ฉ ๐ |
@@ -0,0 +1,35 @@
+package lotto.domain;
+
+import lombok.Getter;
+
+@Getter
+public class PrizeCount {
+
+ private int first;
+ private int second;
+ private int third;
+ private int fourth;
+ private int fifth;
+
+ public void addPrize(Prize prize) {
+ if (prize == Prize.FIRST) {
+ first++;
+ return;
+ }
+ if (prize == Prize.SECOND) {
+ second++;
+ return;
+ }
+ if (prize == Prize.THIRD) {
+ third++;
+ return;
+ }
+ if (prize == Prize.FOURTH) {
+ fourth++;
+ return;
+ }
+ if (prize == Prize.FIFTH) {
+ fifth++;
+ }
+ }
+} | Java | ์ด ํด๋์ค์ ์ด๋ฆ์ด Prize**Count**์ด๋
line 9 to 13 count ๋ ์ค๋ณต์ฒ๋ผ ๋๊ปด์ง๋ค์. ๋ ๋จ์ํ๊ฒ ๋ค์ด๋ฐํด๋ ์๋ฏธ ์ ๋ฌ์ ๋ฌด๋ฆฌ ์์ด๋ณด์
๋๋ค. |
@@ -0,0 +1,17 @@
+package lotto.domain;
+
+import lombok.Builder;
+import lombok.Getter;
+import lotto.domain.dto.WinningLottoInput;
+
+public class WinningLotto extends Lotto {
+
+ @Getter
+ private final LottoNumber bonusNumber;
+
+ @Builder
+ public WinningLotto(WinningLottoInput winningLottoInput) throws IllegalArgumentException {
+ super(winningLottoInput.getNumbers());
+ this.bonusNumber = new LottoNumber(winningLottoInput.getBonus());
+ }
+} | Java | 1. ๋ค์ด๋ฐ์์ Condition๊ณผ ๊ฐ์ ๋ชจํธํ ๋จ์ด๋ฅผ ์ฌ์ฉํ๋ฉด ์ข์ง ์์ต๋๋ค. ๋ ๊ตฌ์ฒด์ ์ธ ํํ์ ์ฌ์ฉํ๋๋ก ํฉ์๋ค.
2. find๋ผ๋ ํํ๊ณผ get์ด๋ผ๋ ํํ ์ฌ์ด์ ๋ฏธ๋ฌํ ์ฐจ์ด๊ฐ ์์ต๋๋ค. ์ด๋ค ์ฐจ์ด์ธ์ง๋ ์ฐพ์์ ๊ณต๋ถํ๊ณ ์ ์๊ฒ๋ ๊ณต์ ํด์ฃผ์ธ์. |
@@ -0,0 +1,22 @@
+package lotto.domain;
+
+import lombok.Builder;
+import lombok.Getter;
+
+public class LottoStatistics {
+
+ @Getter
+ private final PrizeCount prizeCount;
+ private final PurchaseCount purchaseCount;
+
+ @Builder
+ public LottoStatistics(PrizeCount prizeCount, PurchaseCount purchaseCount) {
+ this.prizeCount = prizeCount;
+ this.purchaseCount = purchaseCount;
+ }
+
+ public double calculateProfitRate() {
+ return (double) Prize.sumOfPrizeMoney(prizeCount)
+ / (purchaseCount.getPurchaseCount() * Lotto.PRICE);
+ }
+}
\ No newline at end of file | Java | ํต๊ณ๋ฅผ ๋ด๋ ๊ฐ์ฒด๋ฅผ ๋ง๋ ๊ฒ ์์ฃผ ์ข์ต๋๋ค ๐ |
@@ -0,0 +1,31 @@
+package christmas.model.badge.enums;
+
+import java.util.Arrays;
+
+public enum BadgeInfo {
+
+ SANTA_BADGE("์ฐํ", 20_000),
+ TREE_BADGE("ํธ๋ฆฌ", 10_000),
+ START_BADGE("๋ณ", 5_000),
+ NON_BADGE("์์", 0);
+
+ private final String name;
+
+ private final int price;
+
+ BadgeInfo(String name, int price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public static BadgeInfo findBadgeByPrice(int totalPrice) {
+ return Arrays.stream(values())
+ .filter(badge -> totalPrice >= badge.price)
+ .findFirst()
+ .orElse(NON_BADGE);
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ์ค์๋ฅผ ๋ฏธ์
์ด ๋๋๊ณ ๋ฐ๊ฒฌํ์ต๋๋ค ^^..
START -> STAR |
@@ -0,0 +1,32 @@
+package christmas.model.discount;
+
+
+import static christmas.exception.ErrorType.INVALID_ORDER_AMOUNT;
+import static christmas.model.discount.enums.DiscountAmount.CAN_GIVEAWAY_DISCOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+
+import christmas.model.order.enums.MenuInfo;
+
+public class GiveawayDiscount implements Discount {
+
+ private final int totalOrderAmount;
+
+ public GiveawayDiscount(int totalOrderAmount) {
+ validateOrderAmount(totalOrderAmount);
+ this.totalOrderAmount = totalOrderAmount;
+ }
+
+ private void validateOrderAmount(int totalOrderAmount) {
+ if (totalOrderAmount < NON_DISCOUNT.getDiscount()) {
+ throw new IllegalArgumentException(INVALID_ORDER_AMOUNT.getMessage());
+ }
+ }
+
+ @Override
+ public int calculateDiscount() {
+ if (totalOrderAmount >= CAN_GIVEAWAY_DISCOUNT.getDiscount()) {
+ return MenuInfo.CHRISTMAS_PASTA.getPrice();
+ }
+ return NON_DISCOUNT.getDiscount();
+ }
+} | Java | ์ค์๋ฅผ ๋ฏธ์
์ด ๋๋๊ณ ๋ฐ๊ฒฌํ์ต๋๋ค ^^..
ํ์คํ -> ์ดํ์ธ (๊ฐ๊ฒฉ์ด ๋๊ฐ์์ ๋์น์ฑ์ง ๋ชปํ๋ค์ (__)) |
@@ -0,0 +1,61 @@
+package christmas.model.order.enums;
+
+import static christmas.exception.ErrorType.INVALID_MENU_NOT_EXIST;
+
+import java.util.Arrays;
+
+public enum MenuInfo {
+
+ MUSHROOM_SOUP("์์ก์ด์ํ", 6_000, Category.APPETIZER),
+ TAPAS("ํํ์ค", 5_500, Category.APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, Category.APPETIZER),
+
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, Category.MAIN_COURSE),
+ BARBECUE_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, Category.MAIN_COURSE),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, Category.MAIN_COURSE),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, Category.MAIN_COURSE),
+
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, Category.DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, Category.DESSERT),
+
+ ZERO_COLA("์ ๋ก์ฝ๋ผ", 3_000, Category.BEVERAGE),
+ RED_WINE("๋ ๋์์ธ", 60_000, Category.BEVERAGE),
+ CHAMPAGNE("์ดํ์ธ", 25_000, Category.BEVERAGE);
+
+ private final String name;
+
+ private final int price;
+
+ private final Category category;
+
+ MenuInfo(String name, int price, Category category) {
+ this.name = name;
+ this.price = price;
+ this.category = category;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public Category getCategory() {
+ return category;
+ }
+
+ public static boolean isExistMenu(String name) {
+ return Arrays.stream(MenuInfo.values())
+ .map(MenuInfo::getName)
+ .anyMatch(existMenu -> existMenu.equals(name));
+ }
+
+ public static MenuInfo findByMenuName(String name) {
+ return Arrays.stream(MenuInfo.values())
+ .filter(menuInfo -> menuInfo.getName().equals(name))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(INVALID_MENU_NOT_EXIST.getMessage()));
+ }
+} | Java | ๋ฉ๋ด ์ข
๋ฅ๋ณ ์ฃผ๋ฌธ ์๋์ ์ ์ฅํ๋ Map์ ๋ง๋๋ ๋ฉ์๋๊ฐ ์์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,54 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public abstract class EventCalendar implements Calendar {
+
+ protected final LocalDate eventDate;
+
+ public EventCalendar(int visitDay) {
+ validate(visitDay);
+ this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay);
+ }
+
+ protected abstract void validateDayRange(int visitDay);
+
+ @Override
+ public boolean isWeekend() {
+ int visitDay = getDayOfWeek();
+ return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber();
+ }
+
+ @Override
+ public boolean isSpecialDay() {
+ return isChristmas() || isSunday();
+ }
+
+ @Override
+ public int getDayOfMonth() {
+ return eventDate.getDayOfMonth();
+ }
+
+ private void validate(int visitDay) {
+ validateDayRange(visitDay);
+ }
+
+ private boolean isChristmas() {
+ return getDayOfMonth() == CHRISTMAS.getNumber();
+ }
+
+ private boolean isSunday() {
+ return getDayOfWeek() == SUNDAY.getNumber();
+ }
+
+ private int getDayOfWeek() {
+ return eventDate.getDayOfWeek().getValue();
+ }
+} | Java | `DayOfWeek`๋ `enum` ํ์
์ด๊ธฐ์ ๋ค์๊ณผ ๊ฐ์ด ์ง์ ์ ์ธ ๋๋ฑ์ฑ ๋น๊ต๋ ๊ฐ๋ฅํ๋ฉฐ, ์ด ๊ฒฝ์ฐ๊ฐ ๊ฐ๋
์ฑ๋ ๋ ์ข์์ง ๊ฒ ๊ฐ์ต๋๋ค!
```suggestion
DayOfWeek week = eventDate.getDayOfWeek();
return week == DayOfWeek.FRIDAY || week == DayOfWeek.SATURDAY;
``` |
@@ -0,0 +1,14 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+
+public class CalendarFactory {
+
+ public static Calendar createCalendar(int day) {
+ if (day <= CHRISTMAS.getNumber()) {
+ return new ChristmasEventCalendar(day);
+ }
+
+ return new GeneralEventCalendar(day);
+ }
+} | Java | ์ํ, ์
๋ ฅ ๋ ์ง๊ฐ ํฌ๋ฆฌ์ค๋ง์ค ์ดํ์ธ์ง์ ์ฌ๋ถ์ ๋ฐ๋ผ ๊ฐ๊ฐ ๋ค๋ฅธ `Calendar` ํด๋์ค๋ฅผ ์ฌ์ฉํ๋๋ก ํ์
จ๋ค์.
์ด๋ ๊ฒ๋ ๊ตฌํ์ ํ ์ ์์๊ตฐ์! |
@@ -0,0 +1,31 @@
+package christmas.model.badge.enums;
+
+import java.util.Arrays;
+
+public enum BadgeInfo {
+
+ SANTA_BADGE("์ฐํ", 20_000),
+ TREE_BADGE("ํธ๋ฆฌ", 10_000),
+ START_BADGE("๋ณ", 5_000),
+ NON_BADGE("์์", 0);
+
+ private final String name;
+
+ private final int price;
+
+ BadgeInfo(String name, int price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public static BadgeInfo findBadgeByPrice(int totalPrice) {
+ return Arrays.stream(values())
+ .filter(badge -> totalPrice >= badge.price)
+ .findFirst()
+ .orElse(NON_BADGE);
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๋ฑ์ง๋ฅผ ์ป์ ์ ์๋ ํํ๊ฐ ๊ธ์ก๋ง ์ค์ ํด ๋๊ณ , `enum`์ ์์๋ฅผ ํ์ฉํ์
จ๋ค์!
`enum`์ ์์์ ์ํฅ์ ๋ฐ๋ ๋ก์ง์ ์์ฑํ๋ ๊ฒ์ด ์ณ์๊ฐ ์ ๋ํ ํ์ ์ด ์์ด ์ด๋ ๊ฒ ๊ตฌํํ์ง ๋ชปํ๋๋ฐ, ์ด๋ ๊ฒ ๊ตฌํํ๋ ๊ฒ์ด ํจ์ฌ ๊ฐ๊ฒฐํ๊ณ ์ข์์ ๊ฒ๋ ๊ฐ๊ตฐ์! |
@@ -0,0 +1,20 @@
+package christmas.model.badge;
+
+import christmas.model.badge.enums.BadgeInfo;
+
+public class Badge {
+
+ private final BadgeInfo badgeInfo;
+
+ public Badge(int totalDiscountAmount) {
+ this.badgeInfo = selectBadge(totalDiscountAmount);
+ }
+
+ public String getBadgeName() {
+ return badgeInfo.getName();
+ }
+
+ private BadgeInfo selectBadge(int totalDiscountAmount) {
+ return BadgeInfo.findBadgeByPrice(totalDiscountAmount);
+ }
+} | Java | ํด๋น ํด๋์ค๋ ์ด๋ป๊ฒ ๋ณด๋ฉด `BadgeInfo`๋ฅผ ๋ํํ๊ณ ์๋ ๋ํ ํด๋์ค์ฒ๋ผ ๋ณด์ด๋๋ฐ์.
์ด ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์๋ ์ด๋ค ์ด์ ์ด ์์ ์ ์์๊น์? |
@@ -0,0 +1,15 @@
+package christmas.model.order.enums;
+
+public enum Category {
+
+ APPETIZER("์ํผํ์ด์ "),
+ MAIN_COURSE("๋ฉ์ธ"),
+ DESSERT("๋์ ํธ"),
+ BEVERAGE("์๋ฃ");
+
+ private final String category;
+
+ Category(String category) {
+ this.category = category;
+ }
+} | Java | ํด๋น ํ๋๋ ํ์ฅ์ฑ์ ์ํ ํ๋์ธ๊ฐ์? |
@@ -0,0 +1,51 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MENU_NAME;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class OrderMenu {
+
+ private final Map<MenuName, MenuQuantity> orderMenu;
+
+ public OrderMenu() {
+ this.orderMenu = new HashMap<>();
+ }
+
+ public Map<MenuName, MenuQuantity> getOrderMenu() {
+ return Collections.unmodifiableMap(orderMenu);
+ }
+
+ public int getMenuQuantity(MenuName menuName) {
+ return orderMenu.get(menuName).getQuantity();
+ }
+
+ public boolean containMainMenu(MenuName menuName) {
+ String menu = menuName.getName();
+ return MenuInfo.findByMenuName(menu).getCategory() == Category.MAIN_COURSE;
+ }
+
+ public boolean containDesertMenu(MenuName menuName) {
+ String menu = menuName.getName();
+ return MenuInfo.findByMenuName(menu).getCategory() == Category.DESSERT;
+ }
+
+ public void addMenu(MenuName menuName, MenuQuantity menuQuantity) {
+ validate(menuName);
+ orderMenu.put(menuName, menuQuantity);
+ }
+
+ private void validate(MenuName menuName) {
+ validateDuplicateMenuName(menuName);
+ }
+
+ private void validateDuplicateMenuName(MenuName menuName) {
+ if (orderMenu.containsKey(menuName)) {
+ throw new IllegalArgumentException(INVALID_MENU_NAME.getMessage());
+ }
+ }
+} | Java | ์ด๋ฆ์ `MainMenu`๋ฅผ ํฌํจํ๋์ง๋ฅผ ํ๋จํ๋ ๋ฉ์๋์ฒ๋ผ ๋๊ปด์ง๋๋ฐ, ์๋์ ๋ก์ง์ ์
๋ ฅ๋ฐ์ ๋ฉ๋ด๊ฐ ๋ฉ์ธ๋ฉ๋ด์ธ์ง๋ฅผ ํ๋จํ๋ค์.
`contain~`๋ณด๋ค `is~`์ ๋ค์ด๋ฐ์ด ์กฐ๊ธ ๋ ์ ์ ํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,64 @@
+package christmas.model.result;
+
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+
+public class DiscountResult {
+
+ private int christmasDiscount;
+
+ private int weeksDaysDiscount;
+
+ private int weekendDiscount;
+
+ private int specialDiscount;
+
+ private int giveawayDiscount;
+
+ public DiscountResult() {
+ this.christmasDiscount = NON_DISCOUNT.getDiscount();
+ this.weeksDaysDiscount = NON_DISCOUNT.getDiscount();
+ this.weekendDiscount = NON_DISCOUNT.getDiscount();
+ this.specialDiscount = NON_DISCOUNT.getDiscount();
+ this.giveawayDiscount = NON_DISCOUNT.getDiscount();
+ }
+
+ public void updateChristmasDiscount(int christmasDiscount) {
+ this.christmasDiscount = christmasDiscount;
+ }
+
+ public void updateWeeksDaysDiscount(int weeksDaysDiscount) {
+ this.weeksDaysDiscount = weeksDaysDiscount;
+ }
+
+ public void updateWeekendDiscount(int weekendDiscount) {
+ this.weekendDiscount = weekendDiscount;
+ }
+
+ public void updateSpecialDiscount(int specialDiscount) {
+ this.specialDiscount = specialDiscount;
+ }
+
+ public void updateGiveawayDiscount(int giveawayDiscount) {
+ this.giveawayDiscount = giveawayDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getWeeksDaysDiscount() {
+ return weeksDaysDiscount;
+ }
+
+ public int getWeekendDiscount() {
+ return weekendDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getGiveawayDiscount() {
+ return giveawayDiscount;
+ }
+} | Java | ์ํ, ์ฒ์์ ๋ชจ๋ ํ ์ธ ์ ์ฉ์ 0์ผ๋ก ๋๊ณ ํ ์ธ์ ์ ์ฉํ ์ ์์ ๋ ๋ด๋ถ์ ๊ฐ๋ค์ ์๋ก ์
๋ฐ์ดํธ ํด์ฃผ๋๊ตฐ์!
์ ์๋ ๋ค๋ฅธ ์ ๊ทผ์ด๋ผ์ ์ ๋ง ์ฌ๋ฏธ์๊ฒ ์ฝ์์ต๋๋ค! |
@@ -0,0 +1,81 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY;
+import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK;
+import static christmas.utils.Constants.MAX_ORDER_QUANTITY;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OrderDetail {
+
+ private final OrderMenu orderMenu;
+
+ public OrderDetail(OrderMenu orderMenu) {
+ validate(orderMenu);
+ this.orderMenu = orderMenu;
+ }
+
+ public Map<String, Integer> getOrderMenuName() {
+ Map<String, Integer> details = new HashMap<>();
+ for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) {
+ String menuName = entry.getKey().getName();
+ int quantity = entry.getValue().getQuantity();
+ details.put(menuName, quantity);
+ }
+
+ return Collections.unmodifiableMap(details);
+ }
+
+ public int getQuantityByMenu(MenuName menuName) {
+ return orderMenu.getMenuQuantity(menuName);
+ }
+
+ public List<MenuName> getMainMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containMainMenu)
+ .toList();
+ }
+
+ public List<MenuName> getDesertMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containDesertMenu)
+ .toList();
+ }
+
+ private void validate(OrderMenu orderMenu) {
+ if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) {
+ validateOnlyBeverage(orderMenu);
+ }
+
+ validateMaxQuantity(calculateTotalQuantity(orderMenu));
+ }
+
+ private void validateOnlyBeverage(OrderMenu orderMenu) {
+ MenuName menuName = orderMenu.getOrderMenu().keySet().stream()
+ .findFirst()
+ .orElseThrow();
+
+ String name = menuName.getName();
+ if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) {
+ throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage());
+ }
+ }
+
+ private void validateMaxQuantity(int totalQuantity) {
+ if (totalQuantity > MAX_ORDER_QUANTITY) {
+ throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage());
+ }
+ }
+
+ private int calculateTotalQuantity(OrderMenu orderMenu) {
+ return orderMenu.getOrderMenu().values().stream()
+ .mapToInt(MenuQuantity::getQuantity)
+ .sum();
+ }
+} | Java | ์ด ์ฝ๋์ ํ๋ฆ์ ์ดํดํด ๋ณด๊ณ ์ ์ ๋ง ์ด์ฌํ ๋
ธ๋ ฅํ๋๋ฐ ์คํจํ์ต๋๋ค...ใ
ใ
์ฃผ๋ฌธ ๋ชฉ๋ก์ ์ฒซ ๋ฒ์งธ ๋ฉ๋ด๋ง ์นดํ
๊ณ ๋ฆฌ๋ฅผ ํ์ธํ๋ ๊ฒ์ผ๋ก ํด์์ ํ๋๋ฐ ์ด๊ฒ ์ด๋ป๊ฒ ์๋ฃ๋ง ์ฃผ๋ฌธํ ๊ฒฝ์ฐ๋ฅผ ํ๋ณํ ์ ์๋ ์ง ๋ชจ๋ฅด๊ฒ ์ด์...
๊ด์ฐฎ์ผ์๋ค๋ฉด ํธํ์ค ๋ ์ค๋ช
ํ๋ฒ๋ง ๋ถํ๋๋ฆฝ๋๋ค..! |
@@ -0,0 +1,30 @@
+package christmas.model.calendar;
+
+import static christmas.exception.ErrorType.INVALID_DAY_OUT_OF_RANGE;
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.START_DAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public class ChristmasEventCalendar extends EventCalendar {
+
+ public ChristmasEventCalendar(int visitDay) {
+ super(visitDay);
+ }
+
+ protected void validateDayRange(int visitDay) {
+ if (visitDay < START_DAY.getNumber() || visitDay > CHRISTMAS.getNumber()) {
+ throw new IllegalArgumentException(INVALID_DAY_OUT_OF_RANGE.getMessage());
+ }
+ }
+
+ public int calculateVisitDayFromStart() {
+ int visitDay = getDayOfMonth();
+ return visitDay - START_DAY.getNumber();
+ }
+} | Java | ์กฐ๊ฑด๋ฌธ์ด ๊ธธ์ด์ง๋ค๋ฉด ๋ฉ์๋๋ก ๋ฐ๋ก ๋นผ๋๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,20 @@
+package christmas.model.badge;
+
+import christmas.model.badge.enums.BadgeInfo;
+
+public class Badge {
+
+ private final BadgeInfo badgeInfo;
+
+ public Badge(int totalDiscountAmount) {
+ this.badgeInfo = selectBadge(totalDiscountAmount);
+ }
+
+ public String getBadgeName() {
+ return badgeInfo.getName();
+ }
+
+ private BadgeInfo selectBadge(int totalDiscountAmount) {
+ return BadgeInfo.findBadgeByPrice(totalDiscountAmount);
+ }
+} | Java | ์ ๋ ๊ฐ์ ์๊ฒฌ์
๋๋ค !
`Badge` ํด๋์ค์์ ์ด๋ค์ง๋ ๋ชจ๋ ๋ก์ง์ `BadgeInfo`์์๋ ๋์ผํ๊ธฐ ์ํํ ์ ์๊ณ
๊ทธ๋ ๊ฒ ํ๋ค๋ฉด ํด๋์ค ๋ช
์ Info ๋ฅผ ์ถ๊ฐํ์ง ์์๋ ๋ผ์ ๋์ฑ ๊น๋ํ ์ฝ๋๊ฐ ๋ ๊ฒ ๊ฐ์์ ! |
@@ -0,0 +1,54 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public abstract class EventCalendar implements Calendar {
+
+ protected final LocalDate eventDate;
+
+ public EventCalendar(int visitDay) {
+ validate(visitDay);
+ this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay);
+ }
+
+ protected abstract void validateDayRange(int visitDay);
+
+ @Override
+ public boolean isWeekend() {
+ int visitDay = getDayOfWeek();
+ return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber();
+ }
+
+ @Override
+ public boolean isSpecialDay() {
+ return isChristmas() || isSunday();
+ }
+
+ @Override
+ public int getDayOfMonth() {
+ return eventDate.getDayOfMonth();
+ }
+
+ private void validate(int visitDay) {
+ validateDayRange(visitDay);
+ }
+
+ private boolean isChristmas() {
+ return getDayOfMonth() == CHRISTMAS.getNumber();
+ }
+
+ private boolean isSunday() {
+ return getDayOfWeek() == SUNDAY.getNumber();
+ }
+
+ private int getDayOfWeek() {
+ return eventDate.getDayOfWeek().getValue();
+ }
+} | Java | LocalDate๋ฅผ ํ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์์๊ตฐ์ ..!
๋ ๋ค์ํญ ํ์ฉ์ ํ ์ ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,45 @@
+package christmas.model.discount;
+
+import static christmas.model.discount.enums.DiscountAmount.DESERT_DISCOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.calendar.Calendar;
+import christmas.model.order.MenuName;
+import christmas.model.order.OrderDetail;
+import java.util.List;
+
+public class WeekdaysDiscount implements Discount {
+
+ private final Calendar calendar;
+
+ private final OrderDetail orderDetail;
+
+ public WeekdaysDiscount(Calendar calendar, OrderDetail orderDetail) {
+ this.calendar = calendar;
+ this.orderDetail = orderDetail;
+ }
+
+ @Override
+ public int calculateDiscount() {
+ if (!calendar.isWeekend()) {
+ return desertDiscountPrice();
+ }
+ return NON_DISCOUNT.getDiscount();
+ }
+
+ private int desertDiscountPrice() {
+ List<MenuName> desertMenu = orderDetail.getDesertMenu();
+ int totalPrice = NON_DISCOUNT.getDiscount();
+ if (desertMenu.size() < MIN_ORDER_MENU) {
+ return totalPrice;
+ }
+
+ for (MenuName menuName : desertMenu) {
+ int quantityByMenu = orderDetail.getQuantityByMenu(menuName);
+ totalPrice += (quantityByMenu * DESERT_DISCOUNT.getDiscount());
+ }
+
+ return totalPrice;
+ }
+} | Java | `orderDetail.getDesertMenu()` ์์ ๋์ ํธ ๋ฉ๋ด๊ฐ ์๋ค๋ฉด ๋น ์ปฌ๋ ์
์ด ๋ฐํ๋๊ธฐ ๋๋ฌธ์
์ด ๊ฒ์ฆ ๋ก์ง์ด ์์ด๋ ๊ด์ฐฎ์ง ์์๊น? ๋ผ๋ ์๊ฐ์ด ๋ค์ด์! |
@@ -0,0 +1,45 @@
+package christmas.model.discount;
+
+import static christmas.model.discount.enums.DiscountAmount.MAIN_COURSE_DISCOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.calendar.Calendar;
+import christmas.model.order.MenuName;
+import christmas.model.order.OrderDetail;
+import java.util.List;
+
+public class WeekendDiscount implements Discount {
+
+ private final Calendar calendar;
+
+ private final OrderDetail orderDetail;
+
+ public WeekendDiscount(Calendar calendar, OrderDetail orderDetail) {
+ this.calendar = calendar;
+ this.orderDetail = orderDetail;
+ }
+
+ @Override
+ public int calculateDiscount() {
+ if (calendar.isWeekend()) {
+ return mainCourseDiscountPrice();
+ }
+ return NON_DISCOUNT.getDiscount();
+ }
+
+ private int mainCourseDiscountPrice() {
+ List<MenuName> mainMenu = orderDetail.getMainMenu();
+ int totalPrice = NON_DISCOUNT.getDiscount();
+ if (mainMenu.size() < MIN_ORDER_MENU) {
+ return totalPrice;
+ }
+
+ for (MenuName menuName : mainMenu) {
+ int quantityByMenu = orderDetail.getQuantityByMenu(menuName);
+ totalPrice += (quantityByMenu * MAIN_COURSE_DISCOUNT.getDiscount());
+ }
+
+ return totalPrice;
+ }
+} | Java | ~~~java
mainMenus.strem()
.mapToInt(menu -> orderDetail.getQuantityByMenu(menuName))
.sum()
~~~
๊ณผ ๊ฐ์ด ์คํธ๋ฆผ์ ํ์ฉํด ๋ณด๋ ๊ฒ๋ ์ข์๋ณด์ฌ์! |
@@ -0,0 +1,83 @@
+package christmas.model.discount.facade;
+
+import static christmas.model.discount.enums.DiscountAmount.CAN_DISCOUNT_AMOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+
+import christmas.model.discount.GiveawayDiscount;
+import christmas.model.result.DiscountResult;
+import christmas.model.calendar.Calendar;
+import christmas.model.calendar.ChristmasEventCalendar;
+import christmas.model.discount.ChristmasDiscount;
+import christmas.model.discount.SpecialDiscount;
+import christmas.model.discount.WeekdaysDiscount;
+import christmas.model.discount.WeekendDiscount;
+import christmas.model.order.OrderDetail;
+import christmas.utils.Payment;
+
+public class DiscountFacade {
+
+ private final Calendar calendar;
+
+ private final OrderDetail orderDetail;
+
+ public DiscountFacade(Calendar calendar, OrderDetail orderDetail) {
+ this.calendar = calendar;
+ this.orderDetail = orderDetail;
+ }
+
+ public int calculateTotalDiscount(Payment payment, DiscountResult discountResult) {
+ if (!canDiscount(payment)) {
+ return NON_DISCOUNT.getDiscount();
+ }
+
+ if (includeChristmasDiscount()) {
+ ChristmasDiscount christmasDiscount = new ChristmasDiscount(calendar);
+ int christmasAmount = christmasDiscount.calculateDiscount();
+ discountResult.updateChristmasDiscount(christmasAmount);
+ return christmasAmount + basicDiscount(payment, discountResult);
+ }
+ return basicDiscount(payment, discountResult);
+ }
+
+ private boolean canDiscount(Payment payment) {
+ return payment.beforeDiscountPayment(orderDetail) >= CAN_DISCOUNT_AMOUNT.getDiscount();
+ }
+
+ private int basicDiscount(Payment payment, DiscountResult discountResult) {
+ int weekendAmount = calculateWeekendDiscount();
+ int weekdaysAmount = calculateWeekdaysDiscount();
+ int specialAmount = calculateSpecialDiscount();
+ int giveawayAmount = calculateGiveawayDiscount(payment);
+
+ discountResult.updateWeekendDiscount(weekendAmount);
+ discountResult.updateWeeksDaysDiscount(weekdaysAmount);
+ discountResult.updateSpecialDiscount(calculateSpecialDiscount());
+ discountResult.updateGiveawayDiscount(giveawayAmount);
+
+ return weekendAmount + weekdaysAmount + specialAmount + giveawayAmount;
+ }
+
+ private int calculateWeekendDiscount() {
+ WeekendDiscount weekendDiscount = new WeekendDiscount(calendar, orderDetail);
+ return weekendDiscount.calculateDiscount();
+ }
+
+ private int calculateWeekdaysDiscount() {
+ WeekdaysDiscount weekdaysDiscount = new WeekdaysDiscount(calendar, orderDetail);
+ return weekdaysDiscount.calculateDiscount();
+ }
+
+ private int calculateSpecialDiscount() {
+ SpecialDiscount specialDiscount = new SpecialDiscount(calendar);
+ return specialDiscount.calculateDiscount();
+ }
+
+ private int calculateGiveawayDiscount(Payment payment) {
+ GiveawayDiscount giveawayDiscount = new GiveawayDiscount(payment.beforeDiscountPayment(orderDetail));
+ return giveawayDiscount.calculateDiscount();
+ }
+
+ private boolean includeChristmasDiscount() {
+ return calendar instanceof ChristmasEventCalendar;
+ }
+} | Java | ํ ์ธ ํํ๋ค์ ๋ชจ๋ `Discount`๋ก ์ถ์ํ ํด๋์
จ๊ธฐ ๋๋ฌธ์
~~~java
List<Discount> discounts = List.of(
new WeekendDiscount(calendar, orderDetail),
new WeekdaysDiscount(calendar, orderDetail),
new SpecialDiscount(calendar)
);
int discountAmount = discounts.stream()
.mapToInt(Discount::calculateDiscount)
.sum()
~~~
์ฒ๋ผ ํ์ฉํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค !
์ ๋ ๊ทธ๊ฒ ์ถ์ํ์ ๋ ๋ค๋ฅธ ์ฅ์ ์ด๋ผ๊ณ ์๊ฐํด์! |
@@ -0,0 +1,81 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY;
+import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK;
+import static christmas.utils.Constants.MAX_ORDER_QUANTITY;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OrderDetail {
+
+ private final OrderMenu orderMenu;
+
+ public OrderDetail(OrderMenu orderMenu) {
+ validate(orderMenu);
+ this.orderMenu = orderMenu;
+ }
+
+ public Map<String, Integer> getOrderMenuName() {
+ Map<String, Integer> details = new HashMap<>();
+ for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) {
+ String menuName = entry.getKey().getName();
+ int quantity = entry.getValue().getQuantity();
+ details.put(menuName, quantity);
+ }
+
+ return Collections.unmodifiableMap(details);
+ }
+
+ public int getQuantityByMenu(MenuName menuName) {
+ return orderMenu.getMenuQuantity(menuName);
+ }
+
+ public List<MenuName> getMainMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containMainMenu)
+ .toList();
+ }
+
+ public List<MenuName> getDesertMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containDesertMenu)
+ .toList();
+ }
+
+ private void validate(OrderMenu orderMenu) {
+ if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) {
+ validateOnlyBeverage(orderMenu);
+ }
+
+ validateMaxQuantity(calculateTotalQuantity(orderMenu));
+ }
+
+ private void validateOnlyBeverage(OrderMenu orderMenu) {
+ MenuName menuName = orderMenu.getOrderMenu().keySet().stream()
+ .findFirst()
+ .orElseThrow();
+
+ String name = menuName.getName();
+ if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) {
+ throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage());
+ }
+ }
+
+ private void validateMaxQuantity(int totalQuantity) {
+ if (totalQuantity > MAX_ORDER_QUANTITY) {
+ throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage());
+ }
+ }
+
+ private int calculateTotalQuantity(OrderMenu orderMenu) {
+ return orderMenu.getOrderMenu().values().stream()
+ .mapToInt(MenuQuantity::getQuantity)
+ .sum();
+ }
+} | Java | ์ด๋ฏธ `OrderMenu`๊ฐ ์ผ๊ธ ์ปฌ๋ ์
์ ์ญํ ์ ํ๊ณ ์๋๋ฐ ๊ตณ์ด ํ๋ฒ ๋ ๊ฐ์ธ์ผ ํ๋?? ๋ผ๋ ์๊ฐ์ด ๋ญ๋๋ค..
๊ฐ์ ์ญํ ์ `OrderMenu`๊ฐ ์ํํด๋ ๋ฌธ๋งฅ์ ์ ํ ์ด์ํ์ง ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,54 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public abstract class EventCalendar implements Calendar {
+
+ protected final LocalDate eventDate;
+
+ public EventCalendar(int visitDay) {
+ validate(visitDay);
+ this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay);
+ }
+
+ protected abstract void validateDayRange(int visitDay);
+
+ @Override
+ public boolean isWeekend() {
+ int visitDay = getDayOfWeek();
+ return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber();
+ }
+
+ @Override
+ public boolean isSpecialDay() {
+ return isChristmas() || isSunday();
+ }
+
+ @Override
+ public int getDayOfMonth() {
+ return eventDate.getDayOfMonth();
+ }
+
+ private void validate(int visitDay) {
+ validateDayRange(visitDay);
+ }
+
+ private boolean isChristmas() {
+ return getDayOfMonth() == CHRISTMAS.getNumber();
+ }
+
+ private boolean isSunday() {
+ return getDayOfWeek() == SUNDAY.getNumber();
+ }
+
+ private int getDayOfWeek() {
+ return eventDate.getDayOfWeek().getValue();
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,20 @@
+package christmas.model.badge;
+
+import christmas.model.badge.enums.BadgeInfo;
+
+public class Badge {
+
+ private final BadgeInfo badgeInfo;
+
+ public Badge(int totalDiscountAmount) {
+ this.badgeInfo = selectBadge(totalDiscountAmount);
+ }
+
+ public String getBadgeName() {
+ return badgeInfo.getName();
+ }
+
+ private BadgeInfo selectBadge(int totalDiscountAmount) {
+ return BadgeInfo.findBadgeByPrice(totalDiscountAmount);
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค. ๊ฐ์ฒด์๊ฒ ๋ฉ์ธ์ง๋ฅผ ๋์ ธ์ ์บก์ํ ์ํค๋ ค๊ณ ์๋ํ์๋๋ฐ, ์๋นํ ๋ถํ์ํ๋ค๊ณ ์๊ฐ๋๋ค์ ใ
ใ
|
@@ -0,0 +1,15 @@
+package christmas.model.order.enums;
+
+public enum Category {
+
+ APPETIZER("์ํผํ์ด์ "),
+ MAIN_COURSE("๋ฉ์ธ"),
+ DESSERT("๋์ ํธ"),
+ BEVERAGE("์๋ฃ");
+
+ private final String category;
+
+ Category(String category) {
+ this.category = category;
+ }
+} | Java | ๋ค ๋ง์ต๋๋ค! |
@@ -0,0 +1,81 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY;
+import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK;
+import static christmas.utils.Constants.MAX_ORDER_QUANTITY;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OrderDetail {
+
+ private final OrderMenu orderMenu;
+
+ public OrderDetail(OrderMenu orderMenu) {
+ validate(orderMenu);
+ this.orderMenu = orderMenu;
+ }
+
+ public Map<String, Integer> getOrderMenuName() {
+ Map<String, Integer> details = new HashMap<>();
+ for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) {
+ String menuName = entry.getKey().getName();
+ int quantity = entry.getValue().getQuantity();
+ details.put(menuName, quantity);
+ }
+
+ return Collections.unmodifiableMap(details);
+ }
+
+ public int getQuantityByMenu(MenuName menuName) {
+ return orderMenu.getMenuQuantity(menuName);
+ }
+
+ public List<MenuName> getMainMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containMainMenu)
+ .toList();
+ }
+
+ public List<MenuName> getDesertMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containDesertMenu)
+ .toList();
+ }
+
+ private void validate(OrderMenu orderMenu) {
+ if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) {
+ validateOnlyBeverage(orderMenu);
+ }
+
+ validateMaxQuantity(calculateTotalQuantity(orderMenu));
+ }
+
+ private void validateOnlyBeverage(OrderMenu orderMenu) {
+ MenuName menuName = orderMenu.getOrderMenu().keySet().stream()
+ .findFirst()
+ .orElseThrow();
+
+ String name = menuName.getName();
+ if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) {
+ throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage());
+ }
+ }
+
+ private void validateMaxQuantity(int totalQuantity) {
+ if (totalQuantity > MAX_ORDER_QUANTITY) {
+ throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage());
+ }
+ }
+
+ private int calculateTotalQuantity(OrderMenu orderMenu) {
+ return orderMenu.getOrderMenu().values().stream()
+ .mapToInt(MenuQuantity::getQuantity)
+ .sum();
+ }
+} | Java | ์๋จ์ validate๋ฅผ ๋ณด์๋ฉด ์ดํดํ์ค ์ ์์๊ฑฐ์์..! |
@@ -0,0 +1,63 @@
+package christmas.controller;
+
+import christmas.domain.PromotionService;
+import christmas.domain.order.Day;
+import christmas.domain.order.Order;
+import christmas.dto.response.DiscountPreviewResponse;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionController {
+
+ private PromotionController() {
+
+ }
+
+ public static PromotionController create() {
+ return new PromotionController();
+ }
+
+
+ public void run() {
+ printIntroductionMessage();
+
+ Day day = readWithExceptionHandling(PromotionController::readDay);
+ Order order = readWithExceptionHandling(PromotionController::readOrder);
+ PromotionService promotionService = PromotionService.create(order, day);
+ closeRead();
+
+ printDiscountPreviewMessage(promotionService);
+ }
+
+ private static void printIntroductionMessage() {
+ OutputView.printIntroductionMessage();
+ }
+
+ private static <T> T readWithExceptionHandling(Supplier<T> reader) {
+ while (true) {
+ try {
+ return reader.get();
+ } catch (IllegalArgumentException exception) {
+ System.out.println(exception.getMessage());
+ }
+ }
+ }
+
+ private static Day readDay() throws IllegalArgumentException {
+ return Day.create(InputView.readEstimatedVisitingDate());
+ }
+
+ private static Order readOrder() throws IllegalArgumentException {
+ return Order.create(InputView.readOrder());
+ }
+
+ private static void closeRead() {
+ InputView.closeRead();
+ }
+
+ private static void printDiscountPreviewMessage(PromotionService promotionService) {
+ OutputView.printDiscountPreviewMessage(DiscountPreviewResponse.from(promotionService));
+ }
+} | Java | static ๋ฉ์๋๊ฐ ์๋๊ฐ ๋นจ๋ผ์ง๋ค๋ ์ฅ์ ์ด ์์ง๋ง ๊ฐ์ฒด์งํฅ์์ ๋ฉ์ด์ง๊ธฐ ๋๋ฌธ์ ์ง์ํด์ผํ๋ค๊ณ ์๊ฐํฉ๋๋ค!
ํน์ Controller ๋ด ๋ฉ์๋๋ค์ ๋ชจ๋ static ๋ฉ์๋๋ก ์ ์ธํ์ ์ด์ ๊ฐ ์์ผ์ค๊น์?? |
@@ -0,0 +1,40 @@
+package christmas.domain.order;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Day {
+
+ private final Integer day;
+
+ private Day(Integer day) {
+ validate(day);
+ this.day = day;
+ }
+
+ public static Day create(Integer day) {
+ return new Day(day);
+ }
+
+ private void validate(Integer day) {
+ OrderValidator.validateIsDateInRange(day);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Day day1 = (Day) o;
+ return Objects.equals(day, day1.day);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(day);
+ }
+
+ public Integer getPrimitiveDay() {
+ return day;
+ }
+} | Java | Day ๊ฐ์ฒด์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ OrderValidator์์ ์งํํ๊ฒ ๋๋ฉด ๋๋ฉ์ธ ๋ด๋ถ ์ํ ๋ฐ์ดํฐ์ ์บก์ํ๊ฐ ๊นจ์ง ๋ฟ๋๋ฌ ์ ํจ์ฑ ๊ฒ์ฌ์ ์์ด ๋ง์์ง๋ฉด OrderValidator ๊ฐ์ฒด๊ฐ ๋น๋ํด์ง๋ค๋ ๋จ์ ์ด ์๋ค๊ณ ์๊ฐํฉ๋๋ค.
Day ๊ฐ์ฒด ๋ด๋ถ์์ ์งํํ๋ ๊ฒ์ ์ด๋ค๊ฐ์?? |
@@ -0,0 +1,74 @@
+package christmas.domain.order;
+
+import christmas.domain.order.menu.Menu;
+import christmas.domain.order.menu.Quantity;
+import christmas.dto.request.OrderRequest;
+import christmas.dto.response.OrderResponse;
+import christmas.util.InputUtil;
+import christmas.validator.OrderValidator;
+
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class Order {
+
+ Map<Menu, Quantity> Order;
+
+ private Order(List<OrderRequest> orderRequests) {
+ Map<Menu, Quantity> order = InputUtil.parseOrderRequests(orderRequests);
+ validate(order);
+ this.Order = new EnumMap<>(order);
+ }
+
+ public static Order create(List<OrderRequest> orderRequests) {
+ return new Order(orderRequests);
+ }
+
+ private void validate(Map<Menu, Quantity> order) {
+ OrderValidator.validateHasOnlyDrink(order);
+ OrderValidator.validateIsTotalQuantityValid(order);
+ }
+
+ public List<OrderResponse> findOrderResponses() {
+ return Order
+ .entrySet()
+ .stream()
+ .map(entry -> OrderResponse.of(entry.getKey(), entry.getValue()))
+ .toList();
+ }
+
+ public int calculateInitialPrice() {
+ return Order
+ .entrySet()
+ .stream()
+ .mapToInt(entry -> getMenuPrice(entry) * getEachQuantity(entry))
+ .sum();
+ }
+
+ private int getMenuPrice(Map.Entry<Menu, Quantity> entry) {
+ return entry.getKey().getPrice();
+ }
+
+ private Integer getEachQuantity(Map.Entry<Menu, Quantity> entry) {
+ return entry.getValue().getPrimitiveQuantity();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Order order = (Order) o;
+ return Objects.equals(getOrder(), order.getOrder());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getOrder());
+ }
+
+ public Map<Menu, Quantity> getOrder() {
+ return new EnumMap<>(Order);
+ }
+} | Java | ์ ๊ทผ์ ์ด์๋ฅผ default๋ก ์ ์ธํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,70 @@
+package christmas.domain.order.menu;
+
+import java.util.Arrays;
+import java.util.Map;
+
+public enum Menu {
+
+ // ๊ธฐํ
+ NONE("์์", 0, MenuType.NONE),
+
+ // ์ํผํ์ด์
+ MUSHROOM_SOUP("์์ก์ด ์คํ", 6_000, MenuType.APPETIZER),
+ TAPAS("ํํ์ค", 5_500, MenuType.APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, MenuType.APPETIZER),
+
+ // ๋ฉ์ธ
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MenuType.MAIN),
+ BBQ_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, MenuType.MAIN),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MenuType.MAIN),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MenuType.MAIN),
+
+ // ๋์ ํธ
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, MenuType.DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, MenuType.DESSERT),
+
+ // ์๋ฃ
+ ZERO_COKE("์ ๋ก์ฝ๋ผ", 3_000, MenuType.DRINK),
+ RED_WINE("๋ ๋์์ธ", 60_000, MenuType.DRINK),
+ CHAMPAGNE("์ดํ์ธ", 25_000, MenuType.DRINK);
+
+ private final String name;
+ private final int price;
+ private final MenuType type;
+
+ Menu(String name, int price, MenuType type) {
+ this.name = name;
+ this.price = price;
+ this.type = type;
+ }
+
+ public static Menu findByName(String name) {
+ return Arrays.stream(values())
+ .filter(menu -> menu.name.equals(name))
+ .findAny()
+ .orElse(Menu.NONE);
+ }
+
+ public static boolean isGiftMenu(Menu menu) {
+ return getGiftMenus()
+ .keySet()
+ .stream()
+ .anyMatch(giftMenu -> giftMenu.equals(menu));
+ }
+
+ public static Map<Menu, Quantity> getGiftMenus() {
+ return Map.of(Menu.CHAMPAGNE, Quantity.create(1));
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public MenuType getType() {
+ return type;
+ }
+} | Java | ์ ๊ฒฝ์ฐ 1์ ์ํด ์ด๋ฒคํธ์ ์ด๋ฒคํธ๊ฐ ๋ณ๊ฒฝ๋ ์ ์๋ค ๊ฐ์ ํด Menu ์ธํฐํ์ด์ค๋ฅผ ์ ์ธํ ๋ค ์ํผํ์ด์ , ๋ฉ์ธ, ๋์ ํธ, ์๋ฃ๋ณ๋ก ENUM ๊ฐ์ฒด๋ฅผ ๊ฐ๊ฐ ๋ฐ๋ก ์ ์ธํ์ต๋๋ค!
์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์!
``` java
public interface Menu {
int discount(int day);
String getName();
int getPrice();
}
```
``` java
public enum Appetizer implements Menu {
MUSHROOM_SOUP("์์ก์ด์ํ", 6000),
TAPAS("ํํ์ค", 5500),
CAESAR_SALAD("์์ ์๋ฌ๋", 8000);
private final String name;
private final int price;
Appetizer(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int discount(int day) {
return 0;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
}
``` |
@@ -0,0 +1,40 @@
+package christmas.domain.order.menu;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Quantity {
+
+ private final Integer quantity;
+
+ private Quantity(Integer quantity) {
+ validate(quantity);
+ this.quantity = quantity;
+ }
+
+ public static Quantity create(Integer quantity) {
+ return new Quantity(quantity);
+ }
+
+ private void validate(Integer quantity) {
+ OrderValidator.validateIsEachQuantityGreaterThanCondition(quantity);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Quantity quantity1 = (Quantity) o;
+ return Objects.equals(quantity, quantity1.quantity);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(quantity);
+ }
+
+ public Integer getPrimitiveQuantity() {
+ return quantity;
+ }
+} | Java | int๊ฐ ์๋ Integer๋ก ์ ์ธํด์ฃผ์๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค!๐ค |
@@ -0,0 +1,18 @@
+package christmas.domain.discount;
+
+import christmas.domain.order.Day;
+import christmas.domain.order.Order;
+
+public interface Discount {
+
+ public void calculateDiscountAmount(Order order, Day day);
+
+ public void checkIsAvailableDiscount(Order order, Day day);
+
+ public String getName();
+
+ public int getDiscountAmount();
+
+ public boolean getIsAvailable();
+
+} | Java | ๋คํ์ฑ์ ์ด์ฉํ๋ ์ ๋ง ์ข์ ๋ฐฉ๋ฒ์ด๋ค์ ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค! |
@@ -0,0 +1,119 @@
+package christmas.validator;
+
+import christmas.domain.order.menu.Menu;
+import christmas.dto.request.OrderRequest;
+import christmas.util.InputUtil;
+import christmas.exception.ErrorMessage;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class InputValidator {
+
+ private InputValidator() {
+
+ }
+
+ /*
+ ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ๊ฐ ๊ฒ์ฆ
+ */
+ public static void validateEstimatedVisitingDateInput(String input) {
+ validateIsBlank(input);
+ validateIsDigit(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ์ ์ฒด ๊ฒ์ฆ
+ */
+ public static void validateOrder(String input) {
+ validateOrderInput(input);
+ validateOrderRequest(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ์ ๊ฒ์ฆ
+ */
+ private static void validateOrderInput(String input) {
+ validateIsBlank(input);
+ validateIsRightFormat(input);
+ }
+
+ private static void validateIsRightFormat(String input) {
+ if (!isRightFormat(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isRightFormat(String input) {
+ String regex = ErrorMessage.ORDER_INPUT_REGEX.getMessage();
+ return Pattern.compile(regex)
+ .matcher(input)
+ .matches();
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ํ ๊ฒ์ฆ
+ */
+ private static void validateOrderRequest(String input) {
+ List<OrderRequest> orderRequests = InputUtil.parseOrder(input);
+ validateIsExistingMenu(orderRequests);
+ validateHasDuplicatedMenu(orderRequests);
+ }
+
+ private static void validateIsExistingMenu(List<OrderRequest> orderRequests) {
+ if (!isExistingMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isExistingMenu(List<OrderRequest> orderRequests) {
+ List<String> menuNames = getMenuNames();
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .allMatch(menuNames::contains);
+ }
+
+ private static List<String> getMenuNames() {
+ return Arrays.stream(Menu.values())
+ .map(Menu::getName)
+ .toList();
+ }
+
+ private static void validateHasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ if (hasDuplicatedMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean hasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .distinct()
+ .count() != orderRequests.size();
+ }
+
+ /*
+ ๊ณตํต ๊ฒ์ฆ
+ */
+ private static void validateIsBlank(String input) {
+ if (input.isBlank()) {
+ throw new IllegalArgumentException(ErrorMessage.INPUT_IS_BLANK.getMessage());
+ }
+ }
+
+ private static void validateIsDigit(String input) {
+ if (!isDigit(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_DATE.getMessage());
+ }
+ }
+
+ private static boolean isDigit(String input) {
+ try {
+ Integer.parseInt(input);
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+} | Java | ํ์ฌ InputValidator ๊ฐ์ฒด์์ ์ฌ์ฉ๋๋ ๋ฉ์๋๋ค์ ๋๋ถ๋ถ ํน์ ๋๋ฉ์ธ์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์ํด ์ฌ์ฉ๋๊ณ ์๋๋ฐ ์ธ์คํด์ค ๋ฉ์๋๋ก ์ฌ์ฉํ๋๊ฑด ์ด๋ ์ ๊ฐ์?? |
@@ -0,0 +1,40 @@
+package christmas.domain.order.menu;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Quantity {
+
+ private final Integer quantity;
+
+ private Quantity(Integer quantity) {
+ validate(quantity);
+ this.quantity = quantity;
+ }
+
+ public static Quantity create(Integer quantity) {
+ return new Quantity(quantity);
+ }
+
+ private void validate(Integer quantity) {
+ OrderValidator.validateIsEachQuantityGreaterThanCondition(quantity);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Quantity quantity1 = (Quantity) o;
+ return Objects.equals(quantity, quantity1.quantity);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(quantity);
+ }
+
+ public Integer getPrimitiveQuantity() {
+ return quantity;
+ }
+} | Java | ํฐ ์๋ฏธ๊ฐ ์๋ ๊ฒ์ ์๋๊ณ , null ์ฒ๋ฆฌ์ ๋๋นํ์ฌ Integer๋ฅผ ์ฌ์ฉํ๊ฒ ๋์์ต๋๋ค. ์ฌ์ค ์
๋ ฅ๊ฐ ๊ฒ์ฆ ๋ก์ง์ด ์ด๋ฏธ ์์ด์ null์ด ๋ค์ด๊ฐ ์ผ์ ์์ ๊ฒ ๊ฐ๊ธฐ๋ ํ๋ค์! |
@@ -0,0 +1,119 @@
+package christmas.validator;
+
+import christmas.domain.order.menu.Menu;
+import christmas.dto.request.OrderRequest;
+import christmas.util.InputUtil;
+import christmas.exception.ErrorMessage;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class InputValidator {
+
+ private InputValidator() {
+
+ }
+
+ /*
+ ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ๊ฐ ๊ฒ์ฆ
+ */
+ public static void validateEstimatedVisitingDateInput(String input) {
+ validateIsBlank(input);
+ validateIsDigit(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ์ ์ฒด ๊ฒ์ฆ
+ */
+ public static void validateOrder(String input) {
+ validateOrderInput(input);
+ validateOrderRequest(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ์ ๊ฒ์ฆ
+ */
+ private static void validateOrderInput(String input) {
+ validateIsBlank(input);
+ validateIsRightFormat(input);
+ }
+
+ private static void validateIsRightFormat(String input) {
+ if (!isRightFormat(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isRightFormat(String input) {
+ String regex = ErrorMessage.ORDER_INPUT_REGEX.getMessage();
+ return Pattern.compile(regex)
+ .matcher(input)
+ .matches();
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ํ ๊ฒ์ฆ
+ */
+ private static void validateOrderRequest(String input) {
+ List<OrderRequest> orderRequests = InputUtil.parseOrder(input);
+ validateIsExistingMenu(orderRequests);
+ validateHasDuplicatedMenu(orderRequests);
+ }
+
+ private static void validateIsExistingMenu(List<OrderRequest> orderRequests) {
+ if (!isExistingMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isExistingMenu(List<OrderRequest> orderRequests) {
+ List<String> menuNames = getMenuNames();
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .allMatch(menuNames::contains);
+ }
+
+ private static List<String> getMenuNames() {
+ return Arrays.stream(Menu.values())
+ .map(Menu::getName)
+ .toList();
+ }
+
+ private static void validateHasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ if (hasDuplicatedMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean hasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .distinct()
+ .count() != orderRequests.size();
+ }
+
+ /*
+ ๊ณตํต ๊ฒ์ฆ
+ */
+ private static void validateIsBlank(String input) {
+ if (input.isBlank()) {
+ throw new IllegalArgumentException(ErrorMessage.INPUT_IS_BLANK.getMessage());
+ }
+ }
+
+ private static void validateIsDigit(String input) {
+ if (!isDigit(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_DATE.getMessage());
+ }
+ }
+
+ private static boolean isDigit(String input) {
+ try {
+ Integer.parseInt(input);
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+} | Java | ์ฌํ ํฌ๊ฒ ์๊ฐ์ ์ ํ๋ ๋ถ๋ถ์ธ๋ฐ, ์๋ฌด๋๋ static์ ๋ถ์ฌ์ ์๋ฌด๋ฐ์๋ ์ธ ์ ์๊ฒ ํ๋ ๊ฒ๋ณด๋ค๋ ํ์ํ ๊ณณ์์๋ง ๋ถ๋ฌ์์ ์ฌ์ฉํ๋ ํธ์ด ์ฅ์ ์ด ์๊ฒ ๋ค์! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,63 @@
+package christmas.controller;
+
+import christmas.domain.PromotionService;
+import christmas.domain.order.Day;
+import christmas.domain.order.Order;
+import christmas.dto.response.DiscountPreviewResponse;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionController {
+
+ private PromotionController() {
+
+ }
+
+ public static PromotionController create() {
+ return new PromotionController();
+ }
+
+
+ public void run() {
+ printIntroductionMessage();
+
+ Day day = readWithExceptionHandling(PromotionController::readDay);
+ Order order = readWithExceptionHandling(PromotionController::readOrder);
+ PromotionService promotionService = PromotionService.create(order, day);
+ closeRead();
+
+ printDiscountPreviewMessage(promotionService);
+ }
+
+ private static void printIntroductionMessage() {
+ OutputView.printIntroductionMessage();
+ }
+
+ private static <T> T readWithExceptionHandling(Supplier<T> reader) {
+ while (true) {
+ try {
+ return reader.get();
+ } catch (IllegalArgumentException exception) {
+ System.out.println(exception.getMessage());
+ }
+ }
+ }
+
+ private static Day readDay() throws IllegalArgumentException {
+ return Day.create(InputView.readEstimatedVisitingDate());
+ }
+
+ private static Order readOrder() throws IllegalArgumentException {
+ return Order.create(InputView.readOrder());
+ }
+
+ private static void closeRead() {
+ InputView.closeRead();
+ }
+
+ private static void printDiscountPreviewMessage(PromotionService promotionService) {
+ OutputView.printDiscountPreviewMessage(DiscountPreviewResponse.from(promotionService));
+ }
+} | Java | ์...! ์ ๊ฐ ์ธํ
๋ฆฌ์ ์ด์ ๋ฉ์๋ ๋ถ๋ฆฌ ๋จ์ถํค์ธ option + command + v๋ฅผ ์์ฃผ ์ฌ์ฉํ๋๋ฐ, ๊ทธ ๊ณผ์ ์์ ์๋์ผ๋ก static ๋ฉ์๋๋ก ์ ์ธ๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ ๋ถ ์ง์์ผ๊ฒ ๋ค์ ๐ |
@@ -0,0 +1,40 @@
+package christmas.domain.order;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Day {
+
+ private final Integer day;
+
+ private Day(Integer day) {
+ validate(day);
+ this.day = day;
+ }
+
+ public static Day create(Integer day) {
+ return new Day(day);
+ }
+
+ private void validate(Integer day) {
+ OrderValidator.validateIsDateInRange(day);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Day day1 = (Day) o;
+ return Objects.equals(day, day1.day);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(day);
+ }
+
+ public Integer getPrimitiveDay() {
+ return day;
+ }
+} | Java | ๊ฐ VO์์ ์ด๋ฃจ์ด์ง๋ ๊ฒ์ฆ์ ํ ๊ตฐ๋ฐ์์ ๋ชจ์ ๊ด๋ฆฌํ๋ฉด ํธ๋ฆฌํ ๊ฒ์ด๋ผ ์๊ฐํ์๋๋ฐ, ๋ง์์ฃผ์ ๊ฒ์ฒ๋ผ ์บก์ํ๊ฐ ๊นจ์ง๋ ๋ฌธ์ ๋ ์์ ๋ฟ๋๋ฌ OrderValidator ๊ฐ์ฒด๊ฐ ๋น๋ํด์ง๋ค๋ฉด ๊ฒฐ๊ตญ์ ๋ก์ง์ ๋ถ๋ฆฌํด์ผํ ๊ฒ์ด๊ณ ์ด๋ฌ๋ฉด ํ ๊ณณ์์ ๊ด๋ฆฌํ ์ ์๋ค๋ ์ฅ์ ๋ํ ์ฌ๋ผ์ง ๊ฒ ๊ฐ์ต๋๋ค.
๊ฒฐ๊ตญ์๋ ์ ์ผ ๊ด๋ จ์ฑ์ด ๊น์ VO ๋ด๋ถ์์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํ๋ ๊ฒ์ด ๋ง๊ฒ ๋ค์! ์ข์ ์กฐ์ธ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,74 @@
+package christmas.domain.order;
+
+import christmas.domain.order.menu.Menu;
+import christmas.domain.order.menu.Quantity;
+import christmas.dto.request.OrderRequest;
+import christmas.dto.response.OrderResponse;
+import christmas.util.InputUtil;
+import christmas.validator.OrderValidator;
+
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class Order {
+
+ Map<Menu, Quantity> Order;
+
+ private Order(List<OrderRequest> orderRequests) {
+ Map<Menu, Quantity> order = InputUtil.parseOrderRequests(orderRequests);
+ validate(order);
+ this.Order = new EnumMap<>(order);
+ }
+
+ public static Order create(List<OrderRequest> orderRequests) {
+ return new Order(orderRequests);
+ }
+
+ private void validate(Map<Menu, Quantity> order) {
+ OrderValidator.validateHasOnlyDrink(order);
+ OrderValidator.validateIsTotalQuantityValid(order);
+ }
+
+ public List<OrderResponse> findOrderResponses() {
+ return Order
+ .entrySet()
+ .stream()
+ .map(entry -> OrderResponse.of(entry.getKey(), entry.getValue()))
+ .toList();
+ }
+
+ public int calculateInitialPrice() {
+ return Order
+ .entrySet()
+ .stream()
+ .mapToInt(entry -> getMenuPrice(entry) * getEachQuantity(entry))
+ .sum();
+ }
+
+ private int getMenuPrice(Map.Entry<Menu, Quantity> entry) {
+ return entry.getKey().getPrice();
+ }
+
+ private Integer getEachQuantity(Map.Entry<Menu, Quantity> entry) {
+ return entry.getValue().getPrimitiveQuantity();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Order order = (Order) o;
+ return Objects.equals(getOrder(), order.getOrder());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getOrder());
+ }
+
+ public Map<Menu, Quantity> getOrder() {
+ return new EnumMap<>(Order);
+ }
+} | Java | ์ ๋ ์ง๊ธ ๋ดค๋ค์ใ
ใ
ใ
ใ
private ์ ์ธํด์ผ ๋๋๋ฐ ๊น๋จน์ ๊ฒ ๊ฐ์ต๋๋ค ๐คฃ |
@@ -0,0 +1,70 @@
+package christmas.domain.order.menu;
+
+import java.util.Arrays;
+import java.util.Map;
+
+public enum Menu {
+
+ // ๊ธฐํ
+ NONE("์์", 0, MenuType.NONE),
+
+ // ์ํผํ์ด์
+ MUSHROOM_SOUP("์์ก์ด ์คํ", 6_000, MenuType.APPETIZER),
+ TAPAS("ํํ์ค", 5_500, MenuType.APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, MenuType.APPETIZER),
+
+ // ๋ฉ์ธ
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MenuType.MAIN),
+ BBQ_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, MenuType.MAIN),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MenuType.MAIN),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MenuType.MAIN),
+
+ // ๋์ ํธ
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, MenuType.DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, MenuType.DESSERT),
+
+ // ์๋ฃ
+ ZERO_COKE("์ ๋ก์ฝ๋ผ", 3_000, MenuType.DRINK),
+ RED_WINE("๋ ๋์์ธ", 60_000, MenuType.DRINK),
+ CHAMPAGNE("์ดํ์ธ", 25_000, MenuType.DRINK);
+
+ private final String name;
+ private final int price;
+ private final MenuType type;
+
+ Menu(String name, int price, MenuType type) {
+ this.name = name;
+ this.price = price;
+ this.type = type;
+ }
+
+ public static Menu findByName(String name) {
+ return Arrays.stream(values())
+ .filter(menu -> menu.name.equals(name))
+ .findAny()
+ .orElse(Menu.NONE);
+ }
+
+ public static boolean isGiftMenu(Menu menu) {
+ return getGiftMenus()
+ .keySet()
+ .stream()
+ .anyMatch(giftMenu -> giftMenu.equals(menu));
+ }
+
+ public static Map<Menu, Quantity> getGiftMenus() {
+ return Map.of(Menu.CHAMPAGNE, Quantity.create(1));
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public MenuType getType() {
+ return type;
+ }
+} | Java | ๋ฉ๋ด Enum์๋ ์ด๋ฐ ์์ผ๋ก ์ธํฐํ์ด์ค๋ฅผ ์ ์ฉํ ์ ์๋๋ฐ ์๊ฐํ์ง ๋ชปํ๋ค์! ์ฐธ๊ณ ํ๊ฒ ์ต๋๋ค...! |
@@ -0,0 +1,24 @@
+package nextstep.security.authorization;
+
+import nextstep.security.authentication.Authentication;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.aop.support.AopUtils;
+
+import java.lang.reflect.Method;
+
+public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> {
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) {
+ Method method = invocation.getMethod();
+ Class<?> targetClass = AopUtils.getTargetClass(method.getClass());
+ Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
+ Secured secured = targetMethod.getAnnotation(Secured.class);
+
+ if (authentication.getAuthorities().contains(secured.value())) {
+ return new AuthorizationDecision(true);
+ }
+
+ return new AuthorizationDecision(false);
+ }
+} | Java | Spring AOP ํ๊ฒฝ์์๋ ๋์ ๊ฐ์ฒด๊ฐ ํ๋ก์ ๊ฐ์ฒด๋ก ๊ฐ์ธ์ง ์ ์๊ธฐ ๋๋ฌธ์,
`method.getAnnotation(Secured.class)`๋ฅผ ์ฌ์ฉํ๋ฉด ์ค์ ๊ตฌํ์ฒด์ ๋ฉ์๋์์ ์ ์ธ๋ `@Secured` ์ด๋
ธํ
์ด์
์ ์ฐพ์ง ๋ชปํ ๊ฐ๋ฅ์ฑ์ด ์์ต๋๋ค.method.getAnnotation ์ AopUtils.getMostSpecificMethod() ์ด๋ค ์ฐจ์ด๊ฐ ์์๊น์? ๐ |
@@ -0,0 +1,11 @@
+package nextstep.security.authorization;
+
+import jakarta.servlet.http.HttpServletRequest;
+import nextstep.security.authentication.Authentication;
+
+public class AuthenticatedAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
+ @Override
+ public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) {
+ return new AuthorizationDecision(authentication.isAuthenticated());
+ }
+} | Java | `AuthenticatedAuthorizationManager`๋ ์ธ์ฆ๋ ์ฌ์ฉ์์ ์ ๊ทผ์ ํ์ฉํ ์ง ์ฌ๋ถ๋ฅผ ๊ฒฐ์ ํ๋ ์ธ๊ฐ(Authorization) ์ญํ ์ ํ๋๋ฐ์,
๋๋ฌธ์ `request.setAttribute("username", authentication.getPrincipal());` ๋ ์ธ๊ฐ์ ์ฑ
์์ ๋ฒ์ด๋ ๋์์ผ๋ก ๋ณด์ฌ์ง๋๋ค. ๊ฐ์ ํด ๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์. ๐ |
@@ -1,13 +1,20 @@
package nextstep.app.ui;
+import jakarta.servlet.http.HttpServletRequest;
import nextstep.app.domain.Member;
import nextstep.app.domain.MemberRepository;
+import nextstep.app.exception.UserNotFoundException;
+import nextstep.security.authentication.Authentication;
import nextstep.security.authorization.Secured;
+import nextstep.security.context.SecurityContext;
+import nextstep.security.context.SecurityContextHolder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
+import java.util.Optional;
@RestController
public class MemberController {
@@ -24,6 +31,17 @@ public ResponseEntity<List<Member>> list() {
return ResponseEntity.ok(members);
}
+ @GetMapping("/members/me")
+ public ResponseEntity<Member> get() {
+ Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+ String email = authentication.getPrincipal().toString();
+
+ Member member = memberRepository.findByEmail(email)
+ .orElseThrow(UserNotFoundException::new);
+
+ return ResponseEntity.ok(member);
+ }
+
@Secured("ADMIN")
@GetMapping("/search")
public ResponseEntity<List<Member>> search() { | Java | `request.setAttribute`๋ฅผ ํตํด ๊ฐ์ ์ ์ฅํ๊ณ ๋ค์ ๊ฐ์ ธ์ค๋ ๊ณผ์ ์ ๊ฑฐ์น์ง ์๊ณ ,
SecurityContext์์ ์ง์ ๊ฐ์ ธ์ฌ ์ ์์ ๊ฒ ๊ฐ๋ค์ ๐ |
@@ -0,0 +1,20 @@
+package nextstep.security.authorization;
+
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.http.HttpMethod;
+
+public class MvcRequestMatcher implements RequestMatcher {
+
+ private final HttpMethod method;
+ private final String uri;
+
+ public MvcRequestMatcher(HttpMethod method, String uri) {
+ this.method = method;
+ this.uri = uri;
+ }
+
+ @Override
+ public boolean matches(HttpServletRequest request) {
+ return request.getMethod().equalsIgnoreCase(method.name()) && request.getRequestURI().equalsIgnoreCase(uri);
+ }
+} | Java | `matches()`๋ ์ ๊ท์ ๋งค์นญ์ ์ํํ๋ ๋ฉ์๋ ์ด๋ฏ๋ก, ๋จ์ํ ๋ฌธ์์ด ๋น๊ต์๋ ์ ํฉํ์ง ์์ ๊ฒ ๊ฐ์์.
HTTP ๋ฉ์๋(GET, POST ๋ฑ)๋ ์ ๊ท์์ด ํ์ํ์ง ์์ผ๋ฏ๋ก, `equalsIgnoreCase()`๋ฅผ ์ฌ์ฉํ๋ฉด ์ฑ๋ฅ ๋ฉด์์๋ ๋ ํจ์จ์ ์ผ ๊ฒ ๊ฐ๋ค์ ๐ |
@@ -0,0 +1,25 @@
+package nextstep.security.authorization;
+
+import jakarta.servlet.http.HttpServletRequest;
+import nextstep.security.authentication.Authentication;
+
+import java.util.List;
+
+public class RequestAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
+
+ private final List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries;
+
+ public RequestAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries) {
+ this.requestMatcherEntries = requestMatcherEntries;
+ }
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) {
+ return requestMatcherEntries.stream()
+ .filter(requestMatcherEntry -> requestMatcherEntry.matchRequest(request))
+ .findFirst()
+ .map(RequestMatcherEntry::getEntry)
+ .map(entry -> entry.check(authentication, request))
+ .orElseGet(() -> new AuthorizationDecision(false));
+ }
+} | Java | `orElseGet()` ์ `orElse()`๋ ์ด๋ค ์ฐจ์ด๊ฐ ์์๊น์? ๐ |
@@ -11,29 +11,29 @@
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
-import java.lang.reflect.Method;
-
public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean {
private final Pointcut pointcut;
+ private final AuthorizationManager<MethodInvocation> securedAuthorizationManager;
public SecuredMethodInterceptor() {
this.pointcut = new AnnotationMatchingPointcut(null, Secured.class);
+ this.securedAuthorizationManager = new SecuredAuthorizationManager();
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
- Method method = invocation.getMethod();
- if (method.isAnnotationPresent(Secured.class)) {
- Secured secured = method.getAnnotation(Secured.class);
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication == null) {
- throw new AuthenticationException();
- }
- if (!authentication.getAuthorities().contains(secured.value())) {
- throw new ForbiddenException();
- }
+
+ Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+ if (authentication == null) {
+ throw new AuthenticationException();
}
+
+ AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation);
+ if (!authorizationDecision.isGranted()) {
+ throw new ForbiddenException();
+ }
+
return invocation.proceed();
}
| Java | `@Secured` ์ด๋
ธํ
์ด์
์ด ์กด์ฌํ๋์ง ๋ค์ ๊ฒ์ฌํ๊ณ ์๋๋ฐ์,
์ด๋ฏธ `AnnotationMatchingPointcut`์ ํตํด `@Secured`์ด ๋ถ์ ๋ฉ์๋๋ง ์ธํฐ์
ํธํ๋๋ก ์ค์ ๋์ด ์๊ธฐ ๋๋ฌธ์,
`if (!method.isAnnotationPresent(Secured.class))` ๋ถ๋ถ์ ์ ๊ฑฐํด๋ ๋ ๊ฒ ๊ฐ์์. ๐ |
@@ -17,6 +17,7 @@
import java.util.Set;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@@ -48,7 +49,7 @@ void request_success_with_admin_user() throws Exception {
);
response.andExpect(status().isOk())
- .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(2));
+ .andExpect(jsonPath("$.length()").value(2));
}
@DisplayName("์ผ๋ฐ ์ฌ์ฉ์๊ฐ ์์ฒญํ ๊ฒฝ์ฐ ๊ถํ์ด ์์ด์ผ ํ๋ค.")
@@ -89,4 +90,32 @@ void request_fail_invalid_password() throws Exception {
response.andExpect(status().isUnauthorized());
}
+
+ @DisplayName("์ธ์ฆ๋ ์ฌ์ฉ์๋ ์์ ์ ์ ๋ณด๋ฅผ ์กฐํํ ์ ์๋ค.")
+ @Test
+ void request_success_members_me() throws Exception {
+ String token = Base64.getEncoder().encodeToString((TEST_USER_MEMBER.getEmail() + ":" + TEST_USER_MEMBER.getPassword()).getBytes());
+
+ ResultActions response = mockMvc.perform(get("/members/me")
+ .header("Authorization", "Basic " + token)
+ .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
+ );
+
+ response.andExpect(status().isOk())
+ .andExpect(jsonPath("$.email").value("b@b.com"))
+ .andExpect(jsonPath("$.password").value("password"));
+ }
+
+ @DisplayName("์ธ์ฆ๋์ง ์์ ์ฌ์ฉ์๋ ์์ ์ ์ ๋ณด๋ฅผ ์กฐํํ ์ ์๋ค.")
+ @Test
+ void request_fail_members_me() throws Exception {
+ String token = Base64.getEncoder().encodeToString((TEST_ADMIN_MEMBER.getEmail() + ":" + "invalid").getBytes());
+
+ ResultActions response = mockMvc.perform(get("/members/me")
+ .header("Authorization", "Basic " + token)
+ .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
+ );
+
+ response.andExpect(status().isUnauthorized());
+ }
} | Java | ํ
์คํธ ์ค๋ช
์ด ์๋ชป๋์ด ์๋ค์ ๐ |
@@ -11,29 +11,29 @@
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
-import java.lang.reflect.Method;
-
public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean {
private final Pointcut pointcut;
+ private final AuthorizationManager<MethodInvocation> securedAuthorizationManager;
public SecuredMethodInterceptor() {
this.pointcut = new AnnotationMatchingPointcut(null, Secured.class);
+ this.securedAuthorizationManager = new SecuredAuthorizationManager();
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
- Method method = invocation.getMethod();
- if (method.isAnnotationPresent(Secured.class)) {
- Secured secured = method.getAnnotation(Secured.class);
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication == null) {
- throw new AuthenticationException();
- }
- if (!authentication.getAuthorities().contains(secured.value())) {
- throw new ForbiddenException();
- }
+
+ Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+ if (authentication == null) {
+ throw new AuthenticationException();
}
+
+ AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation);
+ if (!authorizationDecision.isGranted()) {
+ throw new ForbiddenException();
+ }
+
return invocation.proceed();
}
| Java | > ๊ณ ๋ฏผํ ๋ถ๋ถ
> Q. securedAuthorizationManager ๋ก์ง์ด ์ํ๋๋ ์์ ์ด SecuredMethodInterceptor ์์์ ์ํ๋๋ ๊ฒ์ด ๋ง๋์ง ๊ถ๊ธํฉ๋๋ค.
A. AOP๋ฅผ ํตํด ๋ฉ์๋๊ฐ ์คํ๋๊ธฐ ์ ์ ์ธ๊ฐ(Authorization) ๋ก์ง์ ์ํํ๋๋ก ์ ๊ตฌํํด ์ฃผ์
จ๋ค์! ๐
ํน์ ๊ณ ๋ฏผํ๋ ๋ถ๋ถ์ด ์์ผ์
จ๋ค๋ฉด ๋จ๊ฒจ์ฃผ์๋ฉด ์ ๋ ๊ณ ๋ฏผํด๋ณด๊ณ ๋ต๋ณ ๋๋ฆฌ๋๋ก ํ๊ฒ ์ต๋๋ค ๐ |
@@ -0,0 +1,24 @@
+package nextstep.security.authorization;
+
+import nextstep.security.authentication.Authentication;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.aop.support.AopUtils;
+
+import java.lang.reflect.Method;
+
+public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> {
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) {
+ Method method = invocation.getMethod();
+ Class<?> targetClass = AopUtils.getTargetClass(method.getClass());
+ Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
+ Secured secured = targetMethod.getAnnotation(Secured.class);
+
+ if (authentication.getAuthorities().contains(secured.value())) {
+ return new AuthorizationDecision(true);
+ }
+
+ return new AuthorizationDecision(false);
+ }
+} | Java | AopUtils.getMostSpecificMethod() ๋ก ์ค์ ๋ฉ์๋์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ฌ ์ ์๊ฒ ๋ค์!
๊ทธ๋๋ ์ด๋
ธํ
์ด์
์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ ค๋ฉด getAnnotation ๋ฉ์๋๋ ๊ณ์ ์ฌ์ฉํด์ผ ํ๋ ๊ฑฐ์ฃ ?
์์ ํด๋ดค๋๋ฐ ๋ง๋ ๋ฐฉ์์ธ์ง ํ์ธ ๋ถํ๋๋ฆฝ๋๋ค! |
@@ -0,0 +1,20 @@
+package nextstep.security.authorization;
+
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.http.HttpMethod;
+
+public class MvcRequestMatcher implements RequestMatcher {
+
+ private final HttpMethod method;
+ private final String uri;
+
+ public MvcRequestMatcher(HttpMethod method, String uri) {
+ this.method = method;
+ this.uri = uri;
+ }
+
+ @Override
+ public boolean matches(HttpServletRequest request) {
+ return request.getMethod().equalsIgnoreCase(method.name()) && request.getRequestURI().equalsIgnoreCase(uri);
+ }
+} | Java | ์ ๊ฐ ์ matches๋ฅผ ์ฌ์ฉํ๋์ง ๋ชจ๋ฅด๊ฒ ๋ค์.. ๊ผผ๊ผผํ ๋ฆฌ๋ทฐ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -11,29 +11,29 @@
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
-import java.lang.reflect.Method;
-
public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean {
private final Pointcut pointcut;
+ private final AuthorizationManager<MethodInvocation> securedAuthorizationManager;
public SecuredMethodInterceptor() {
this.pointcut = new AnnotationMatchingPointcut(null, Secured.class);
+ this.securedAuthorizationManager = new SecuredAuthorizationManager();
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
- Method method = invocation.getMethod();
- if (method.isAnnotationPresent(Secured.class)) {
- Secured secured = method.getAnnotation(Secured.class);
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication == null) {
- throw new AuthenticationException();
- }
- if (!authentication.getAuthorities().contains(secured.value())) {
- throw new ForbiddenException();
- }
+
+ Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+ if (authentication == null) {
+ throw new AuthenticationException();
}
+
+ AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation);
+ if (!authorizationDecision.isGranted()) {
+ throw new ForbiddenException();
+ }
+
return invocation.proceed();
}
| Java | ๋ค๋ฅธ AuthorizationManager ๋ค์ Filter์์ ์ธ๊ฐ ๋ก์ง์ด ์ํ๋๋๋ฐ ์ด์ ๋ค๋ฅด๊ฒ AOP๋ฅผ ํตํด ์ํ๋๋ ๋ก์ง์ด์ด์ ๋ง๋ ๋ฐฉ์์ธ์ง ๊ถ๊ธํ์์ต๋๋ค..! ๋ต๋ณ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,25 @@
+package nextstep.security.authorization;
+
+import jakarta.servlet.http.HttpServletRequest;
+import nextstep.security.authentication.Authentication;
+
+import java.util.List;
+
+public class RequestAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
+
+ private final List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries;
+
+ public RequestAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager>> requestMatcherEntries) {
+ this.requestMatcherEntries = requestMatcherEntries;
+ }
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, HttpServletRequest request) {
+ return requestMatcherEntries.stream()
+ .filter(requestMatcherEntry -> requestMatcherEntry.matchRequest(request))
+ .findFirst()
+ .map(RequestMatcherEntry::getEntry)
+ .map(entry -> entry.check(authentication, request))
+ .orElseGet(() -> new AuthorizationDecision(false));
+ }
+} | Java | orElse๋ก ๊ตฌํํ๊ฒ ๋๋ฉด, null์ด ์๋์ด๋ AuthorizationDecision ๊ฐ์ฒด ์์ฑ ๋ก์ง์ ์ํ๋ ๊ฒ ๊ฐ๋ค์.
orElseGet์ผ๋ก ์์ ํ์ต๋๋ค! |
@@ -0,0 +1,24 @@
+package nextstep.security.authorization;
+
+import nextstep.security.authentication.Authentication;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.aop.support.AopUtils;
+
+import java.lang.reflect.Method;
+
+public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> {
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) {
+ Method method = invocation.getMethod();
+ Class<?> targetClass = AopUtils.getTargetClass(method.getClass());
+ Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
+ Secured secured = targetMethod.getAnnotation(Secured.class);
+
+ if (authentication.getAuthorities().contains(secured.value())) {
+ return new AuthorizationDecision(true);
+ }
+
+ return new AuthorizationDecision(false);
+ }
+} | Java | method.getClass()๋ Method ํด๋์ค ์์ฒด์ ํ์
์ ๋ฐํํ๋ฏ๋ก, ์ฌ๋ฐ๋ฅธ ๋์ ํด๋์ค(Target Class)๋ฅผ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค.
invocation.getThis()๋ฅผ ์ฌ์ฉํ์ฌ ์ค์ ๋์ ๊ฐ์ฒด(Target Object)์ ํด๋์ค๋ฅผ ๊ฐ์ ธ์ค๋ ๊ฒ์ด ์ข๊ฒ ๋ค์ ๐
`Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());` |
@@ -0,0 +1,24 @@
+package nextstep.security.authorization;
+
+import nextstep.security.authentication.Authentication;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.aop.support.AopUtils;
+
+import java.lang.reflect.Method;
+
+public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> {
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) {
+ Method method = invocation.getMethod();
+ Class<?> targetClass = AopUtils.getTargetClass(method.getClass());
+ Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
+ Secured secured = targetMethod.getAnnotation(Secured.class);
+
+ if (authentication.getAuthorities().contains(secured.value())) {
+ return new AuthorizationDecision(true);
+ }
+
+ return new AuthorizationDecision(false);
+ }
+} | Java | ๋ค ๋ง์ต๋๋ค
์ด๋
ธํ
์ด์
์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ ๊ฒ์ ๋์ผํ๊ฒ getAnnotation(Secured.class)์ ์ฌ์ฉํด์ผ ํฉ๋๋ค. ๐ |
@@ -11,29 +11,29 @@
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
-import java.lang.reflect.Method;
-
public class SecuredMethodInterceptor implements MethodInterceptor, PointcutAdvisor, AopInfrastructureBean {
private final Pointcut pointcut;
+ private final AuthorizationManager<MethodInvocation> securedAuthorizationManager;
public SecuredMethodInterceptor() {
this.pointcut = new AnnotationMatchingPointcut(null, Secured.class);
+ this.securedAuthorizationManager = new SecuredAuthorizationManager();
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
- Method method = invocation.getMethod();
- if (method.isAnnotationPresent(Secured.class)) {
- Secured secured = method.getAnnotation(Secured.class);
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication == null) {
- throw new AuthenticationException();
- }
- if (!authentication.getAuthorities().contains(secured.value())) {
- throw new ForbiddenException();
- }
+
+ Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+ if (authentication == null) {
+ throw new AuthenticationException();
}
+
+ AuthorizationDecision authorizationDecision = securedAuthorizationManager.check(authentication, invocation);
+ if (!authorizationDecision.isGranted()) {
+ throw new ForbiddenException();
+ }
+
return invocation.proceed();
}
| Java | Filter ๊ธฐ๋ฐ ์ธ๊ฐ๋ HTTP ์์ฒญ ๋จ์์์ ์ ์ฉ๋์ง๋ง,
`@Secured`๋ ๊ฐ๋ณ ๋ฉ์๋ ํธ์ถ ๋จ์์์ ๋ณด์ ๊ฒ์ฌ๋ฅผ ํด์ผ ํด์ ์ ์ ํ ๊ตฌํ ๋ฐฉ์์
๋๋ค ๐ |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ์ด๋ค TextField์ธ์ง ๋ช
์ ์ํด์ฃผ๊ณ editing์ด ์์๋ textField์๋ ์๋์ผ๋ก ์ ์ฉ๋๋๊ตฌ๋
์ค ์๊ฐ๋ชปํ๋๋ฐ ๋ฐฐ์ ์ต๋๋ค ใ
ใ
๊ฐ์ฌํด์ |
@@ -0,0 +1,205 @@
+//
+// LoginView.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/16.
+//
+
+import UIKit
+
+class LoginView: UIView {
+
+ // MARK: - Object Setting
+
+ private let mainLabel = UILabel().then {
+ $0.text = "TVING ID ๋ก๊ทธ์ธ"
+ $0.font = .tvingMedium(ofSize: 23)
+ $0.textColor = .tvingGray1
+ $0.textAlignment = .center
+ }
+
+ let idTextField = CustomTextField().then {
+ $0.placeholder = "์ด๋ฉ์ผ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .emailAddress
+ }
+
+ let idInvalidLabel = UILabel().then {
+ $0.textColor = .systemRed
+ $0.font = .systemFont(ofSize: 12)
+ $0.text = "* ์ฌ๋ฐ๋ฅด์ง ์์ ์ด๋ฉ์ผ ํ์์
๋๋ค ๐ญ"
+ $0.isHidden = true
+ }
+
+ let passwordTextField = CustomPasswordTextField().then {
+ $0.placeholder = "๋น๋ฐ๋ฒํธ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .asciiCapable
+ }
+
+ lazy var logInBtn = UIButton().then {
+ $0.setTitle("๋ก๊ทธ์ธํ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.layer.borderColor = UIColor.tvingGray4.cgColor
+ $0.layer.borderWidth = 1
+ $0.layer.cornerRadius = 3
+ $0.isEnabled = false
+ }
+
+ private let idPasswordStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 40
+ }
+
+ lazy var findIdBtn = UIButton().then {
+ $0.setTitle("์์ด๋ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ lazy var findPasswordBtn = UIButton().then {
+ $0.setTitle("๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ private let makeAccountStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 20
+ }
+
+ let askExistAccountLabel = UILabel().then {
+ $0.text = "์์ง ๊ณ์ ์ด ์์ผ์ ๊ฐ์?"
+ $0.font = .tvingRegular(ofSize: 14)
+ $0.textColor = .tvingGray3
+ $0.textAlignment = .center
+ }
+
+ lazy var goToMakeNicknameBtn = UIButton().then {
+ $0.setTitle("๋๋ค์ ๋ง๋ค๋ฌ๊ฐ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingRegular(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.setUnderline()
+ }
+
+ lazy var backBtn = UIButton().then {
+ $0.setImage(UIImage(named: "btn_before"), for: .normal)
+ }
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+
+ style()
+ hierarchy()
+ setLayout()
+ }
+
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+}
+
+private extension LoginView {
+
+ func style() {
+ self.backgroundColor = .black
+ }
+
+ func hierarchy() {
+ self.addSubviews(mainLabel,
+ idTextField,
+ idInvalidLabel,
+ passwordTextField,
+ logInBtn,
+ idPasswordStackView,
+ makeAccountStackView,
+ backBtn)
+ idPasswordStackView.addArrangedSubviews(findIdBtn,
+ findPasswordBtn)
+ makeAccountStackView.addArrangedSubviews(askExistAccountLabel,
+ goToMakeNicknameBtn)
+ }
+
+
+ func setLayout() {
+
+ mainLabel.snp.makeConstraints{
+ $0.height.equalTo(37)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(50)
+ $0.leading.trailing.equalToSuperview().inset(100)
+ }
+
+ idTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainLabel.snp.bottom).offset(31)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ passwordTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ logInBtn.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(passwordTextField.snp.bottom).offset(21)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ idPasswordStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(logInBtn.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(80)
+ }
+
+ makeAccountStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(50)
+ }
+
+ backBtn.snp.makeConstraints{
+ $0.height.equalTo(15)
+ $0.width.equalTo(8)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(25)
+ $0.leading.equalToSuperview().inset(24)
+ }
+
+ findIdBtn.snp.makeConstraints{
+ $0.width.equalTo(70)
+ $0.height.equalTo(22)
+ }
+
+ findPasswordBtn.snp.makeConstraints{
+ $0.width.equalTo(80)
+ $0.height.equalTo(22)
+ }
+
+ askExistAccountLabel.snp.makeConstraints{
+ $0.width.equalTo(140)
+ $0.height.equalTo(22)
+ }
+
+ goToMakeNicknameBtn.snp.makeConstraints{
+ $0.width.equalTo(128)
+ $0.height.equalTo(22)
+ }
+ }
+} | Swift | ๊ฐ๊ฐ ์ข์ฐ๋ฅผ ๊ธฐ์ค์ผ๋ก ํ๋ฉด ๊ธฐ๊ธฐ๋ง๋ค ์ฐจ์ด๊ฐ ์ข ๋ํ๋ ๊ฑฐ ๊ฐ์์!
๊ฐ์ด๋ฐ๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฌถ์ ์ ์๋ ๋ฐฉ๋ฒ(stackview)๋ ์ข์ ๊ฑฐ๊ฐ์์ ใ
ใ
|
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | UIView๋ฅผ ๋ฐ๋ก ๋นผ๋๊น ํ ์ฝ๋๊ฐ ์งง์์ก๋ค์
์ ๋ ๋ค์์ ์ด๋ฐ์์ผ๋ก ํด๋ด์ผ๊ฒ ์ต๋๋ค ๊ฐ์ฌํฉ๋๋ค ใ
ใ
|
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | targetํจ์ ๋ฐ๋ก ๋บ ๊ฑฐ ์งฑ์ด์์ฌ ๋ฐฐ์๊ฐ๋๋ค |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ์ฐ์ ํค๋ณด๋ ์ฒ๋ฆฌ๊น์ง !! ์งฑ์ด๊ตฐ์ฌ |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ์ ๊ตฌ์กฐ์ฒด๋ก ๋ฌถ์ด์ฃผ๋ ๊ฑฐ ๊น์ง! |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ๊ตฌ์กฐ์ฒด์์ ๋ณ์๋ค์ ""๋ก ์ด๊ธฐํํ๋ ๊ฒ๋ณด๋ค ์ต์
๋ ์ฒ๋ฆฌํด๋๋๊ฒ ์ด๋จ๊น์?
๋์ค์ ๊ตฌ์กฐ์ฒด ๋ณ์์ ๊ฐ์ ๋ฃ๋ค๋ณด๋ฉด, ๋ณ์๊ฐ ์ค์ ๋ก ๊ฐ์ด ์๋ ์ํ์ธ์ง ์๋๋ฉด ์๋์ ์ผ๋ก ๋น ๊ฐ์ผ๋ก ์ด๊ธฐํ๋ ๊ฒ์ธ์ง๋ฅผ
๊ตฌ๋ถํ๊ธฐ ์ด๋ ต๋ค๊ณ ์๊ฐํด์ ์ ๋ ?(์ต์
๋)์ ์ฌ์ฉํด๋ณด๋ฉด ์ข์๊ฒ ๊ฐ์์!
`var id: String?` ์ด๋ฐ ์์ผ๋ก์ |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ์ค์ํํธ์์ ์ ๊ทผ ์ ์ด์๋ฅผ ๋ฐ๋ก ์ ์ธํ์ง ์์ผ๋ฉด internal ์ ๊ทผ์ด ๊ธฐ๋ณธ์ด๋ผ๊ณ ํด์!
open-> public -> internal -> file-private -> private ์ผ๋ก ๊ฐ ์๋ก ์ ํ์ ์ธ ์ ๊ทผ์์ธ๋ฐ
์๋ก ๋ค๋ฅธ ๋ชจ๋๋ผ๋ฆฌ ์ ๊ทผํ๋ ์ํฉ์ด ์๋๋ผ๋ฉด
๊ตณ์ด public์ ์ ์ธํ์ฌ ์ ๊ทผ ์์ค์ ์ฝํ๊ฒ ํ ํ์ ์๋ค๊ณ ์๊ฐํ๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์ธ์ฉ?
https://zeddios.tistory.com/383 |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | public์ด ์๋ก ๋ค๋ฅธ ๋ชจ๋์์๋ ์ ๊ทผํ ์ ์๋๋กํ๋ ์ ๊ทผ ์ ์ด๋ผ๊ณ ํ๋ค์.
๋ชจ๋์ด ์์ํด์ ์ฐพ์๋ณด๋ "Xcode์ ๊ฐ ๋น๋ ๋์"์ ๋ชจ๋์ด๋ผ๊ณ ํ๋๋ผ๊ณ ์. ํ๋ก์ ํธ ํ์ผ์ด๋ผ๊ณ ์ ๋ ์ดํดํ์ด์! |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ?? ๋ฐฉ์์ผ๋ก ์ต์
๋ ์ธ๋ฉํํ๋๊ฒ๋ ์ข์ง๋ง!
๊ฐ๋
์ฑ์ ์ํด if let ์ด๋ guard let์ ์ฐ๋ฉด ๋ ์ข์๊ฒ ๊ฐ์์~ |
@@ -0,0 +1,205 @@
+//
+// LoginView.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/16.
+//
+
+import UIKit
+
+class LoginView: UIView {
+
+ // MARK: - Object Setting
+
+ private let mainLabel = UILabel().then {
+ $0.text = "TVING ID ๋ก๊ทธ์ธ"
+ $0.font = .tvingMedium(ofSize: 23)
+ $0.textColor = .tvingGray1
+ $0.textAlignment = .center
+ }
+
+ let idTextField = CustomTextField().then {
+ $0.placeholder = "์ด๋ฉ์ผ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .emailAddress
+ }
+
+ let idInvalidLabel = UILabel().then {
+ $0.textColor = .systemRed
+ $0.font = .systemFont(ofSize: 12)
+ $0.text = "* ์ฌ๋ฐ๋ฅด์ง ์์ ์ด๋ฉ์ผ ํ์์
๋๋ค ๐ญ"
+ $0.isHidden = true
+ }
+
+ let passwordTextField = CustomPasswordTextField().then {
+ $0.placeholder = "๋น๋ฐ๋ฒํธ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .asciiCapable
+ }
+
+ lazy var logInBtn = UIButton().then {
+ $0.setTitle("๋ก๊ทธ์ธํ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.layer.borderColor = UIColor.tvingGray4.cgColor
+ $0.layer.borderWidth = 1
+ $0.layer.cornerRadius = 3
+ $0.isEnabled = false
+ }
+
+ private let idPasswordStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 40
+ }
+
+ lazy var findIdBtn = UIButton().then {
+ $0.setTitle("์์ด๋ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ lazy var findPasswordBtn = UIButton().then {
+ $0.setTitle("๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ private let makeAccountStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 20
+ }
+
+ let askExistAccountLabel = UILabel().then {
+ $0.text = "์์ง ๊ณ์ ์ด ์์ผ์ ๊ฐ์?"
+ $0.font = .tvingRegular(ofSize: 14)
+ $0.textColor = .tvingGray3
+ $0.textAlignment = .center
+ }
+
+ lazy var goToMakeNicknameBtn = UIButton().then {
+ $0.setTitle("๋๋ค์ ๋ง๋ค๋ฌ๊ฐ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingRegular(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.setUnderline()
+ }
+
+ lazy var backBtn = UIButton().then {
+ $0.setImage(UIImage(named: "btn_before"), for: .normal)
+ }
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+
+ style()
+ hierarchy()
+ setLayout()
+ }
+
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+}
+
+private extension LoginView {
+
+ func style() {
+ self.backgroundColor = .black
+ }
+
+ func hierarchy() {
+ self.addSubviews(mainLabel,
+ idTextField,
+ idInvalidLabel,
+ passwordTextField,
+ logInBtn,
+ idPasswordStackView,
+ makeAccountStackView,
+ backBtn)
+ idPasswordStackView.addArrangedSubviews(findIdBtn,
+ findPasswordBtn)
+ makeAccountStackView.addArrangedSubviews(askExistAccountLabel,
+ goToMakeNicknameBtn)
+ }
+
+
+ func setLayout() {
+
+ mainLabel.snp.makeConstraints{
+ $0.height.equalTo(37)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(50)
+ $0.leading.trailing.equalToSuperview().inset(100)
+ }
+
+ idTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainLabel.snp.bottom).offset(31)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ passwordTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ logInBtn.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(passwordTextField.snp.bottom).offset(21)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ idPasswordStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(logInBtn.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(80)
+ }
+
+ makeAccountStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(50)
+ }
+
+ backBtn.snp.makeConstraints{
+ $0.height.equalTo(15)
+ $0.width.equalTo(8)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(25)
+ $0.leading.equalToSuperview().inset(24)
+ }
+
+ findIdBtn.snp.makeConstraints{
+ $0.width.equalTo(70)
+ $0.height.equalTo(22)
+ }
+
+ findPasswordBtn.snp.makeConstraints{
+ $0.width.equalTo(80)
+ $0.height.equalTo(22)
+ }
+
+ askExistAccountLabel.snp.makeConstraints{
+ $0.width.equalTo(140)
+ $0.height.equalTo(22)
+ }
+
+ goToMakeNicknameBtn.snp.makeConstraints{
+ $0.width.equalTo(128)
+ $0.height.equalTo(22)
+ }
+ }
+} | Swift | ๋ฒํผ ์ปดํฌ๋ํธ๋ค์๋ง lazy๋ฅผ ๋ฃ์ด์ฃผ์
จ๋๋ฐ addTarget์์ (๋
ธ๋์)์๋์ ํผํ๊ธฐ ์ํด์ ๋ฃ์๊ฑฐ์ฃ ..?
๋ฒํผ ์ด๋ฒคํธ ์ฐ๊ฒฐ ๋ฐฉ์์ค์ addTarget ๋ฐฉ์ ์ธ์๋ addAction ๋ฐฉ์๋ ์์ด์!
addAction ๋ฐฉ์์ ์ฌ์ฉํ๋ฉด ๋ฒํผ ์ด๋ฒคํธ ์ฐ๊ฒฐ ํจ์์ @objc๋ ๋ถ์ด์ง ์์๋ ๋๊ณ , ์๋์ ํผํ๊ธฐ ์ํ lazy๋ ์์จ๋ ๋ฉ๋๋ค!
๊ฐ๋
์ฑ ์ธก๋ฉด์ด๋, ์ต๋ํ objc ์์๋ฅผ ์ ์ธํ๊ณ UIKit ํต์ผ์ฑ์ ์ํด addAction ๋ฐฉ์๋ ์๊ณ ์์ผ๋ฉด ์ข์๊ฒ ๊ฐ์์!
์๋๋ addAction ๋ฐฉ์์ผ๋ก ๋ฒํผ ์ด๋ฒคํธ ์ฐ๊ฒฐํ ์์ ์ฝ๋์์!
private func setButtonEvent() {
self.datePickerView.setAction()
let moveToTodayDateButtonAction = UIAction { [weak self] _ in
self?.moveToTodayDate()
}
let moveToTodayDatePickerButtonAction = UIAction { [weak self] _ in
self?.moveToDatePicker()
}
let moveToSettingViewAction = UIAction { [weak self] _ in
self?.moveToSettingView()
}
self.homeCalenderView.todayButton.addAction(moveToTodayDateButtonAction, for: .touchUpInside)
self.homeCalenderView.calendarMonthLabelButton.addAction(moveToTodayDatePickerButtonAction, for: .touchUpInside)
self.homeCalenderView.calendarMonthPickButton.addAction(moveToTodayDatePickerButtonAction, for: .touchUpInside)
self.profileButton.addAction(moveToSettingViewAction, for: .touchUpInside)
} |
@@ -0,0 +1,205 @@
+//
+// LoginView.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/16.
+//
+
+import UIKit
+
+class LoginView: UIView {
+
+ // MARK: - Object Setting
+
+ private let mainLabel = UILabel().then {
+ $0.text = "TVING ID ๋ก๊ทธ์ธ"
+ $0.font = .tvingMedium(ofSize: 23)
+ $0.textColor = .tvingGray1
+ $0.textAlignment = .center
+ }
+
+ let idTextField = CustomTextField().then {
+ $0.placeholder = "์ด๋ฉ์ผ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .emailAddress
+ }
+
+ let idInvalidLabel = UILabel().then {
+ $0.textColor = .systemRed
+ $0.font = .systemFont(ofSize: 12)
+ $0.text = "* ์ฌ๋ฐ๋ฅด์ง ์์ ์ด๋ฉ์ผ ํ์์
๋๋ค ๐ญ"
+ $0.isHidden = true
+ }
+
+ let passwordTextField = CustomPasswordTextField().then {
+ $0.placeholder = "๋น๋ฐ๋ฒํธ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .asciiCapable
+ }
+
+ lazy var logInBtn = UIButton().then {
+ $0.setTitle("๋ก๊ทธ์ธํ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.layer.borderColor = UIColor.tvingGray4.cgColor
+ $0.layer.borderWidth = 1
+ $0.layer.cornerRadius = 3
+ $0.isEnabled = false
+ }
+
+ private let idPasswordStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 40
+ }
+
+ lazy var findIdBtn = UIButton().then {
+ $0.setTitle("์์ด๋ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ lazy var findPasswordBtn = UIButton().then {
+ $0.setTitle("๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ private let makeAccountStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 20
+ }
+
+ let askExistAccountLabel = UILabel().then {
+ $0.text = "์์ง ๊ณ์ ์ด ์์ผ์ ๊ฐ์?"
+ $0.font = .tvingRegular(ofSize: 14)
+ $0.textColor = .tvingGray3
+ $0.textAlignment = .center
+ }
+
+ lazy var goToMakeNicknameBtn = UIButton().then {
+ $0.setTitle("๋๋ค์ ๋ง๋ค๋ฌ๊ฐ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingRegular(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.setUnderline()
+ }
+
+ lazy var backBtn = UIButton().then {
+ $0.setImage(UIImage(named: "btn_before"), for: .normal)
+ }
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+
+ style()
+ hierarchy()
+ setLayout()
+ }
+
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+}
+
+private extension LoginView {
+
+ func style() {
+ self.backgroundColor = .black
+ }
+
+ func hierarchy() {
+ self.addSubviews(mainLabel,
+ idTextField,
+ idInvalidLabel,
+ passwordTextField,
+ logInBtn,
+ idPasswordStackView,
+ makeAccountStackView,
+ backBtn)
+ idPasswordStackView.addArrangedSubviews(findIdBtn,
+ findPasswordBtn)
+ makeAccountStackView.addArrangedSubviews(askExistAccountLabel,
+ goToMakeNicknameBtn)
+ }
+
+
+ func setLayout() {
+
+ mainLabel.snp.makeConstraints{
+ $0.height.equalTo(37)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(50)
+ $0.leading.trailing.equalToSuperview().inset(100)
+ }
+
+ idTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainLabel.snp.bottom).offset(31)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ passwordTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ logInBtn.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(passwordTextField.snp.bottom).offset(21)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ idPasswordStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(logInBtn.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(80)
+ }
+
+ makeAccountStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(50)
+ }
+
+ backBtn.snp.makeConstraints{
+ $0.height.equalTo(15)
+ $0.width.equalTo(8)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(25)
+ $0.leading.equalToSuperview().inset(24)
+ }
+
+ findIdBtn.snp.makeConstraints{
+ $0.width.equalTo(70)
+ $0.height.equalTo(22)
+ }
+
+ findPasswordBtn.snp.makeConstraints{
+ $0.width.equalTo(80)
+ $0.height.equalTo(22)
+ }
+
+ askExistAccountLabel.snp.makeConstraints{
+ $0.width.equalTo(140)
+ $0.height.equalTo(22)
+ }
+
+ goToMakeNicknameBtn.snp.makeConstraints{
+ $0.width.equalTo(128)
+ $0.height.equalTo(22)
+ }
+ }
+} | Swift | ์ด๊ฑด ์ ๊ฐ ์์ฃผ ์ฌ์ฉํ๋ ๋ฐฉ์์ธ๋ฐ
addSubviews ํ ๋ ๊ฐ๋ก๋ก ๊ธธ๊ฒ ์ฐ๋๊ฒ ๋ณด๋ค ์๋ ์ฝ๋์ฒ๋ผ ์ธ๋ก๋ก ๋๋ฆฌ๋๊ฒ ๊ฐ๋
์ฑ์ ์ข๋๋ผ๊ณ ์.
๋ฌผ๋ก ์ฝ๋ ์ค์ ๋์ด๋์ง๋ง์! ๊ฐ์ ์ ํธํ๋ ์คํ์ผ์ด ์๋๊ฒ ๊ฐ์๋ฐ ์กฐ์ฌ์ค๋ .. ์ ์ํด๋ด
๋๋ค ใ
ใ
view.addSubviews(toolBarView,
titleLabelStackView,
houseImageView,
homeGroupLabel,
homeGroupCollectionView,
homeRuleView,
homeDivider,
datePickerView,
homeCalenderView,
homeWeekCalendarCollectionView,
calendarDailyTableView,
emptyHouseWorkImage) |
@@ -0,0 +1,45 @@
+//
+// WelcomeViewController.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/12.
+//
+
+import UIKit
+
+final class WelcomeViewController: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = WelcomeView()
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.goToMainBtn.addTarget(self, action: #selector(tappedGoToMainBtn), for: .touchUpInside)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ }
+}
+
+extension WelcomeViewController {
+
+ func idDataBind(idOrNick: String) {
+ mainView.welcomeLabel.text = "\(idOrNick)๋\n๋ฐ๊ฐ์์!"
+ }
+
+ @objc
+ func tappedGoToMainBtn() {
+ self.navigationController?.popToRootViewController(animated: true)
+ }
+} | Swift | ์ ๊ฐ ์ต๊ทผ์ ์๊ฐ ์์ด ๋ฒํผ ์ด๋ฒคํธ ์ฐ๊ฒฐ ํจ์ ํธ์ถ์ viewWillAppear ์ชฝ์์ ํ๋ค๊ฐ... ๋ฌธ์ ๊ฐ ์๊ฒผ๋๋ฐ
viewDidLoad์ ๋๋ฌด ์ ํด๋์
จ๋ค์ ^~^ |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ๋ ์ด์ ์์๋์ง ์๋ ํด๋์ค๋ผ๋ฉด final ํค์๋ ๋ถ์ด๋ฉด ์ข์๊ฒ ๊ฐ์์! |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ์ฌ๊ธฐ์ didSet์ ์ฌ์ฉํด์ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด ์ข์๊ฑฐ ๊ฐ์์ฉ ์๋ ๋์ถฉ ์์๋ฅผ ์ ์๋๋ฐ ์ ์์ ๋ didSet์ ์ ํ์ฉํ์ง ๋ชปํด์
@meltsplit @seungchan2 ํ์ธ ๋ถํ๋๋ฆฝ๋๋ค
```Swift
public var nickName: String = โ" {
didSet {
guard let nickName = nickNameBottomSheet.nickNameTextFeild.text else { return }
self.nickName = nickName
}
}
``` |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ์ต์
๋ ์ฒ๋ฆฌ์ ๋ํด ๊ณต๋ถํ๋๊ฑด ๋ถ๋ช
๋์ค์ ์ข์ ์์ฐ์ด ๋ ๊ฑฐ์์ฌ! |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ๋ฒํผ ํ์ฑํ์ ์ ๊ท์์ ๋ง๋์ง ํ์ธํ๋ ๋ถ๋ถ์ ๋๋ ์ฃผ๋ฉด ๋ ์ข์๊ฑฐ ๊ฐ์์
๋ฒํผ ํ์ฑํ๋ -> textFeild์ ๊ธ์ด ์ฐจ ์์ ๊ฒฝ์ฐ -> textFeildDidChange๋ฅผ ์ฌ์ฉํ๋ฉด ์ข์๊ฑฐ ๊ฐ๊ณ
์ ๊ท์ ํ์ธ -> ๋ฒํผ์ ๋๋ ์ ๋ -> ๋ฒํผ์ addTarget์ ํด์ ํ์ธํด์ฃผ๋ toastMessage๋ print๋ฌธ์ ์ฐ์ด์ฃผ๋๊ฒ ์ข์๊ฑฐ ๊ฐ์ต๋๋ค~ |
@@ -0,0 +1,119 @@
+//
+// AddNickNameBottomSheetUIView.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/15.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+final class AddNickNameBottomSheetUIView: UIView {
+
+ let bottomSheetHeight = UIScreen.main.bounds.height / 2
+
+ let dimmendView = UIView().then {
+ $0.backgroundColor = .black.withAlphaComponent(0.5)
+ }
+
+ private lazy var dragIndicatior = UIView().then {
+ $0.backgroundColor = .tvingGray1
+ $0.layer.cornerRadius = 3
+ }
+
+ let bottomSheetView = UIView().then {
+ $0.backgroundColor = .white
+ $0.layer.cornerRadius = 12
+ $0.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] // ์ข์ฐ์ธก ํ๋จ์ ๊ทธ๋๋ก
+ }
+
+ private let nickNameMainLabel = UILabel().then {
+ $0.text = "๋๋ค์์ ์
๋ ฅํด์ฃผ์ธ์"
+ $0.font = .tvingMedium(ofSize: 23)
+ }
+
+ let nickNameTextField = CustomTextField().then {
+ $0.placeholder = "๋๋ค์"
+ $0.setPlaceholderColor(.tvingGray1)
+ $0.textColor = .black
+ $0.backgroundColor = .tvingGray2
+ $0.font = .tvingMedium(ofSize: 14)
+ }
+
+ lazy var saveNickNameBtn = UIButton().then {
+ $0.setTitle("์ ์ฅํ๊ธฐ", for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 16)
+ $0.titleLabel?.textAlignment = .center
+ $0.titleLabel?.textColor = .tvingGray2
+ $0.backgroundColor = .black
+ $0.layer.cornerRadius = 12
+ $0.isEnabled = false
+ }
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+
+ style()
+ hierarchy()
+ setLayout()
+ }
+
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+}
+
+private extension AddNickNameBottomSheetUIView {
+
+ func style() {
+
+ }
+
+ func hierarchy() {
+ self.addSubviews(dimmendView,
+ dragIndicatior,
+ bottomSheetView)
+ bottomSheetView.addSubviews(nickNameMainLabel,
+ nickNameTextField,
+ saveNickNameBtn)
+ }
+
+ func setLayout() {
+
+ dimmendView.snp.makeConstraints {
+ $0.edges.equalToSuperview()
+ }
+
+ bottomSheetView.snp.makeConstraints {
+ $0.height.equalTo(bottomSheetHeight)
+ $0.bottom.left.right.equalToSuperview()
+ $0.top.equalToSuperview().inset(UIScreen.main.bounds.height - bottomSheetHeight)
+ }
+
+ dragIndicatior.snp.makeConstraints {
+ $0.height.equalTo(5)
+ $0.leading.trailing.equalToSuperview().inset(120)
+ $0.bottom.equalTo(bottomSheetView.snp.top).inset(-10)
+ }
+
+ nickNameMainLabel.snp.makeConstraints {
+ $0.top.equalToSuperview().inset(45)
+ $0.leading.equalToSuperview().inset(20)
+ }
+
+ nickNameTextField.snp.makeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(nickNameMainLabel.snp.bottom).offset(21)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ saveNickNameBtn.snp.makeConstraints {
+ $0.height.equalTo(52)
+ $0.bottom.equalToSuperview().inset(20)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+
+} | Swift | ์ ๊ทผ ์ ์ด์๋ฅผ ํ์ฉํ ๋๋ ๋ด๊ฐ ํด๋น ๋ด์ฉ์(? ๋ช
์นญ์ด ์ ๋งคํจ) ์ฌ์ฉํ ์ต์ํ์ ๋ฒ์๋ก ์ฌ์ฉํ๋๊ฒ ์ข์์! ๋ง์ฝ ํด๋น ํ์ผ์์๋ง ์ฌ์ฉํ component๋ผ๋ฉด private์ผ๋ก ๋ฐ๊พธ๋๊ฒ๋ ์ข๊ฒ ์ฃ ? |
@@ -0,0 +1,205 @@
+//
+// LoginView.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/16.
+//
+
+import UIKit
+
+class LoginView: UIView {
+
+ // MARK: - Object Setting
+
+ private let mainLabel = UILabel().then {
+ $0.text = "TVING ID ๋ก๊ทธ์ธ"
+ $0.font = .tvingMedium(ofSize: 23)
+ $0.textColor = .tvingGray1
+ $0.textAlignment = .center
+ }
+
+ let idTextField = CustomTextField().then {
+ $0.placeholder = "์ด๋ฉ์ผ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .emailAddress
+ }
+
+ let idInvalidLabel = UILabel().then {
+ $0.textColor = .systemRed
+ $0.font = .systemFont(ofSize: 12)
+ $0.text = "* ์ฌ๋ฐ๋ฅด์ง ์์ ์ด๋ฉ์ผ ํ์์
๋๋ค ๐ญ"
+ $0.isHidden = true
+ }
+
+ let passwordTextField = CustomPasswordTextField().then {
+ $0.placeholder = "๋น๋ฐ๋ฒํธ"
+ $0.setPlaceholderColor(.tvingGray2)
+ $0.font = .tvingMedium(ofSize: 15)
+ $0.textColor = .tvingGray2
+ $0.backgroundColor = .tvingGray4
+ $0.keyboardType = .asciiCapable
+ }
+
+ lazy var logInBtn = UIButton().then {
+ $0.setTitle("๋ก๊ทธ์ธํ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.layer.borderColor = UIColor.tvingGray4.cgColor
+ $0.layer.borderWidth = 1
+ $0.layer.cornerRadius = 3
+ $0.isEnabled = false
+ }
+
+ private let idPasswordStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 40
+ }
+
+ lazy var findIdBtn = UIButton().then {
+ $0.setTitle("์์ด๋ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ lazy var findPasswordBtn = UIButton().then {
+ $0.setTitle("๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingMedium(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ }
+
+ private let makeAccountStackView = UIStackView().then {
+ $0.axis = .horizontal
+ $0.distribution = .fill
+ $0.alignment = .center
+ $0.spacing = 20
+ }
+
+ let askExistAccountLabel = UILabel().then {
+ $0.text = "์์ง ๊ณ์ ์ด ์์ผ์ ๊ฐ์?"
+ $0.font = .tvingRegular(ofSize: 14)
+ $0.textColor = .tvingGray3
+ $0.textAlignment = .center
+ }
+
+ lazy var goToMakeNicknameBtn = UIButton().then {
+ $0.setTitle("๋๋ค์ ๋ง๋ค๋ฌ๊ฐ๊ธฐ", for: .normal)
+ $0.setTitleColor(.tvingGray2, for: .normal)
+ $0.titleLabel?.font = .tvingRegular(ofSize: 14)
+ $0.titleLabel?.textAlignment = .center
+ $0.setUnderline()
+ }
+
+ lazy var backBtn = UIButton().then {
+ $0.setImage(UIImage(named: "btn_before"), for: .normal)
+ }
+
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+
+ style()
+ hierarchy()
+ setLayout()
+ }
+
+ required init?(coder: NSCoder) {
+ fatalError("init(coder:) has not been implemented")
+ }
+
+}
+
+private extension LoginView {
+
+ func style() {
+ self.backgroundColor = .black
+ }
+
+ func hierarchy() {
+ self.addSubviews(mainLabel,
+ idTextField,
+ idInvalidLabel,
+ passwordTextField,
+ logInBtn,
+ idPasswordStackView,
+ makeAccountStackView,
+ backBtn)
+ idPasswordStackView.addArrangedSubviews(findIdBtn,
+ findPasswordBtn)
+ makeAccountStackView.addArrangedSubviews(askExistAccountLabel,
+ goToMakeNicknameBtn)
+ }
+
+
+ func setLayout() {
+
+ mainLabel.snp.makeConstraints{
+ $0.height.equalTo(37)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(50)
+ $0.leading.trailing.equalToSuperview().inset(100)
+ }
+
+ idTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainLabel.snp.bottom).offset(31)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ passwordTextField.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ logInBtn.snp.makeConstraints{
+ $0.height.equalTo(52)
+ $0.top.equalTo(passwordTextField.snp.bottom).offset(21)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+
+ idPasswordStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(logInBtn.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(80)
+ }
+
+ makeAccountStackView.snp.makeConstraints {
+ $0.height.equalTo(25)
+ $0.top.equalTo(idPasswordStackView.snp.bottom).offset(30)
+ $0.centerX.equalToSuperview().inset(50)
+ }
+
+ backBtn.snp.makeConstraints{
+ $0.height.equalTo(15)
+ $0.width.equalTo(8)
+ $0.top.equalTo(self.safeAreaLayoutGuide).inset(25)
+ $0.leading.equalToSuperview().inset(24)
+ }
+
+ findIdBtn.snp.makeConstraints{
+ $0.width.equalTo(70)
+ $0.height.equalTo(22)
+ }
+
+ findPasswordBtn.snp.makeConstraints{
+ $0.width.equalTo(80)
+ $0.height.equalTo(22)
+ }
+
+ askExistAccountLabel.snp.makeConstraints{
+ $0.width.equalTo(140)
+ $0.height.equalTo(22)
+ }
+
+ goToMakeNicknameBtn.snp.makeConstraints{
+ $0.width.equalTo(128)
+ $0.height.equalTo(22)
+ }
+ }
+} | Swift | ์ด์ฉ์ง ๋ ์ด์์ ์ก์ผ๋ฉด์๋ ์ด๊ฒ ๋ง๋.. ์ถ์์ด๋ฏธ๋ค
์คํ๋ทฐ๋ก ๋ค์ ์ง๋ดค์ด์!!!!!! |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | bottomSheet ๋๋ฌธ์ ์ด์ฉ๋ค๋ณด๋..
์ฅ๋จ์ ์ด ์๋ ๊ฒ ๊ฐ์์!!! ์ฝ๋๋ ์ง์ง ๊ฐ๊ฒฐํด์ก์ฃต |
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | bottomSheet๋ฅผ ์ฌ๋ฆฌ๋ ค๊ณ ์ฌ์ฉํ๋๋ฐ ์ด๊ฒ ๋ง๋์ง๋ ๋ฉ๊ฒ ใ
๋ค์..ใ
ใ
|
@@ -0,0 +1,261 @@
+//
+// LoginViewController_TVING.swift
+// GO_SOPT_Seminar_Assingment
+//
+// Created by ๊น๋ค์ on 2023/04/11.
+//
+
+import UIKit
+
+import SnapKit
+import Then
+
+struct TvingUserInfo {
+ var id: String?
+ var password: String?
+ var nickName: String?
+}
+
+final class LoginViewController_TVING: BaseViewController {
+
+ // MARK: - Property
+
+ private let mainView = LoginView()
+ private let nickNameBottomSheet = AddNickNameBottomSheetUIView()
+
+ var user = TvingUserInfo()
+
+ private var bottomSheetKeyboardEnable: Bool = false
+
+ // MARK: - Target
+
+ private func target() {
+ mainView.idTextField.delegate = self
+ mainView.passwordTextField.delegate = self
+
+ mainView.idTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+ mainView.passwordTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ mainView.logInBtn.addTarget(self, action: #selector(tappedLogInBtn), for: .touchUpInside)
+ mainView.goToMakeNicknameBtn.addTarget(self, action: #selector(tappedMakeNickNameBtn), for: .touchUpInside)
+ }
+
+ private func targetBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.delegate = self
+
+ nickNameBottomSheet.nickNameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .allEditingEvents)
+
+ nickNameBottomSheet.saveNickNameBtn.addTarget(self, action: #selector(tappedSavedNickNameBtn), for: .touchUpInside)
+
+ let bottomSheetBackgroundTap = UITapGestureRecognizer(target: self, action: #selector(TappedBottomSheetBackground))
+ nickNameBottomSheet.dimmendView.addGestureRecognizer(bottomSheetBackgroundTap)
+ }
+
+ // MARK: - Lift Cycle
+
+ override func loadView() {
+ self.view = mainView
+ view.addSubview(nickNameBottomSheet)
+
+ nickNameBottomSheet.snp.makeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ target()
+ targetBottomSheet()
+ setKeyboardObserver() // ํค๋ณด๋ ํ์ฑํ์ ๋ฐ๋ฅธ bottomSheet ๋์ด ์กฐ์ ์ํด
+ }
+
+ override func viewWillAppear(_ animated: Bool) {
+ initView()
+ }
+
+}
+
+private extension LoginViewController_TVING {
+
+ // MARK: - objc func
+
+ @objc
+ func tappedLogInBtn() {
+ saveUserEmail()
+ let welcomViewController = WelcomeViewController()
+ welcomViewController.idDataBind(idOrNick: getNickNameOrId())
+ self.navigationController?.pushViewController(welcomViewController, animated: true)
+ }
+
+ @objc
+ func tappedMakeNickNameBtn() {
+ showBottomSheet()
+ }
+
+ @objc
+ func tappedSavedNickNameBtn() {
+ saveUserNickName()
+ hideBottomSheet()
+ }
+
+ @objc func TappedBottomSheetBackground(_ tapRecognizer: UITapGestureRecognizer) {
+ hideBottomSheet()
+ }
+
+ @objc func keyboardWillShow(notification: NSNotification) {
+ guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - (nickNameBottomSheet.bottomSheetHeight + keyboardSize.height)
+ }
+ }
+
+ @objc func keyboardWillHide(notification: NSNotification) {
+ if (nickNameBottomSheet.nickNameTextField.isSelected){
+ bottomSheetKeyboardEnable = true
+ nickNameBottomSheet.bottomSheetView.frame.origin.y = UIScreen.main.bounds.height - nickNameBottomSheet.bottomSheetHeight
+ }
+ }
+
+ // MARK: - custom func
+
+ func saveUserEmail(){
+ guard let id = mainView.idTextField.text else { return }
+ user.id = id
+ }
+
+ func saveUserNickName() {
+ guard let nickName = nickNameBottomSheet.nickNameTextField.text else { return }
+ user.nickName = nickName
+ }
+
+ func getNickNameOrId() -> String {
+ if let nickName = user.nickName {
+ return nickName
+ } else {
+ guard let id = user.id else { return "" }
+ return id
+ }
+ }
+
+ func isIDValid() -> Bool {
+ guard let id = mainView.idTextField.text else { return false }
+ return id.isValidEmail()
+ }
+
+ func showBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = true
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.edges.equalToSuperview()
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height)
+ })
+ }
+
+ func hideBottomSheet() {
+ nickNameBottomSheet.nickNameTextField.isSelected = false
+ nickNameBottomSheet.snp.remakeConstraints {
+ $0.width.equalToSuperview()
+ $0.top.equalTo(view.snp.bottom)
+ }
+ UIView.animate(withDuration: 0.5, animations: {
+ self.nickNameBottomSheet.frame = CGRect(x: 0.0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
+ }
+ )
+ }
+
+ func initView() {
+ mainView.idTextField.text = nil
+ mainView.passwordTextField.text = nil
+ nickNameBottomSheet.nickNameTextField.text = nil
+ user = TvingUserInfo()
+ mainView.logInBtn.enableDisableButtonSet(isEnable: false, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ func setKeyboardObserver() {
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
+ NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
+ }
+
+}
+
+// MARK: - TextFieldDelegate
+
+extension LoginViewController_TVING: UITextFieldDelegate {
+
+ // textField๊ฐ ํ์ฑํ๋๋ฉด
+ func textFieldDidBeginEditing(_ textField: UITextField) {
+ textField.layer.borderColor = UIColor.tvingGray2.cgColor
+ textField.layer.borderWidth = 0.7
+ }
+
+ // textField ๋นํ์ฑํ๋๋ฉด
+ func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
+ textField.layer.borderWidth = 0
+
+ idValidPrint()
+
+ return true
+ }
+
+ @objc
+ private func textFieldDidChange(_ textField: UITextField) {
+
+ if let nickNameText = nickNameBottomSheet.nickNameTextField.text {
+ if (!nickNameText.isValidNickName()) {
+ nickNameBottomSheet.nickNameTextField.text = nil
+ }
+ }
+
+ let idPwIsFull: Bool = mainView.idTextField.hasText && !mainView.passwordTextField.hasText
+ let saveIdPwBtnEnable: Bool = idPwIsFull && isIDValid()
+
+ if (saveIdPwBtnEnable) {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ mainView.logInBtn.enableDisableButtonSet(isEnable: saveIdPwBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+
+ let saveNickNameBtnEnable = !nickNameBottomSheet.nickNameTextField.hasText
+
+ if (saveNickNameBtnEnable) {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .tvingRed, setTextColor: .white)
+ }else {
+ nickNameBottomSheet.saveNickNameBtn.enableDisableButtonSet(isEnable: saveNickNameBtnEnable, setColor: .black, setTextColor: .tvingGray2)
+ }
+ }
+
+ private func idValidPrint() {
+
+ if (!(mainView.idTextField.text?.isValidEmail() ?? false) && !mainView.idTextField.hasText) {
+ mainView.idTextField.layer.borderColor = UIColor.tvingRed.cgColor
+ mainView.idTextField.layer.borderWidth = 0.7
+
+ mainView.idInvalidLabel.isHidden = false
+ mainView.idInvalidLabel.snp.remakeConstraints {
+ $0.leading.equalTo(mainView.idTextField.snp.leading)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(5)
+ }
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(30)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ } else {
+ mainView.idTextField.layer.borderWidth = 0
+
+ mainView.idInvalidLabel.isHidden = true
+
+ mainView.passwordTextField.snp.remakeConstraints {
+ $0.height.equalTo(52)
+ $0.top.equalTo(mainView.idTextField.snp.bottom).offset(7)
+ $0.leading.trailing.equalToSuperview().inset(20)
+ }
+ }
+ }
+
+} | Swift | ๋ด์ ๋ฆฌ๋ทฐ ๋ฐ๋ก ๋ฌ๋ฌ๊ฐ๊ฒ์ฉ~๐ |
@@ -0,0 +1,67 @@
+import { Button, Form, Input, Select, Space } from 'antd';
+import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants';
+import useMembers from '@apis/review/useMembers';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { ReviewCycle } from '@apis/review/entities';
+
+interface Props {
+ onFinish: (values: ReviewCycleRequest) => void;
+ onReset: () => void;
+ initialValues?: {
+ name: ReviewCycle['name'];
+ reviewees: number[];
+ title: ReviewCycle['question']['title'];
+ description: ReviewCycle['question']['description'];
+ };
+ confirmButtonProps?: { text: string };
+ deleteButtonProps?: { text: string; handleClick: () => void };
+}
+
+export default function ReviewCycleForm({
+ onFinish,
+ onReset,
+ initialValues,
+ confirmButtonProps = { text: 'ํ์ธ' },
+ deleteButtonProps,
+}: Props) {
+ const { members, isLoading } = useMembers();
+
+ return (
+ <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}>
+ <Form.Item label="๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}>
+ <Select
+ mode="multiple"
+ loading={isLoading}
+ placeholder="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํด์ฃผ์ธ์."
+ optionFilterProp="label"
+ options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))}
+ />
+ </Form.Item>
+
+ <Form.Item label="์ง๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item
+ label="์ง๋ฌธ ์ค๋ช
"
+ name={REVIEW_CYCLE_FORM_NAMES.question.description}
+ rules={REVIEW_CYCLE_RULES.questionDescription}
+ >
+ <Input />
+ </Form.Item>
+ <Form.Item style={{ textAlign: 'right' }}>
+ <Space size={10}>
+ <Button htmlType="reset">์ทจ์</Button>
+ {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>}
+ <Button type="primary" htmlType="submit">
+ {confirmButtonProps.text}
+ </Button>
+ </Space>
+ </Form.Item>
+ </Form>
+ );
+} | Unknown | ์๊ธฐ `form`์ ์์ด๋ ๋ ๊ฒ ๊ฐ์์~ |
@@ -0,0 +1,67 @@
+import { Button, Form, Input, Select, Space } from 'antd';
+import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants';
+import useMembers from '@apis/review/useMembers';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { ReviewCycle } from '@apis/review/entities';
+
+interface Props {
+ onFinish: (values: ReviewCycleRequest) => void;
+ onReset: () => void;
+ initialValues?: {
+ name: ReviewCycle['name'];
+ reviewees: number[];
+ title: ReviewCycle['question']['title'];
+ description: ReviewCycle['question']['description'];
+ };
+ confirmButtonProps?: { text: string };
+ deleteButtonProps?: { text: string; handleClick: () => void };
+}
+
+export default function ReviewCycleForm({
+ onFinish,
+ onReset,
+ initialValues,
+ confirmButtonProps = { text: 'ํ์ธ' },
+ deleteButtonProps,
+}: Props) {
+ const { members, isLoading } = useMembers();
+
+ return (
+ <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}>
+ <Form.Item label="๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}>
+ <Select
+ mode="multiple"
+ loading={isLoading}
+ placeholder="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํด์ฃผ์ธ์."
+ optionFilterProp="label"
+ options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))}
+ />
+ </Form.Item>
+
+ <Form.Item label="์ง๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item
+ label="์ง๋ฌธ ์ค๋ช
"
+ name={REVIEW_CYCLE_FORM_NAMES.question.description}
+ rules={REVIEW_CYCLE_RULES.questionDescription}
+ >
+ <Input />
+ </Form.Item>
+ <Form.Item style={{ textAlign: 'right' }}>
+ <Space size={10}>
+ <Button htmlType="reset">์ทจ์</Button>
+ {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>}
+ <Button type="primary" htmlType="submit">
+ {confirmButtonProps.text}
+ </Button>
+ </Space>
+ </Form.Item>
+ </Form>
+ );
+} | Unknown | ์ค ์ด๋ฐ ๋ฐฉ์์ผ๋ก ํ์ดํ ํ๋ฉด `initialValues`์ ๋ํ ํ์
์ ๋ฐ๋ก ๋ง๋ค์ด์ฃผ์ง ์์๋ ๋๊ณ ์ข๋ค์ ๐ |
@@ -0,0 +1,17 @@
+import { Rule } from 'antd/lib/form';
+
+export const REVIEW_CYCLE_FORM_NAMES = {
+ name: 'name',
+ reviewees: 'reviewees',
+ question: {
+ title: 'title',
+ description: 'description',
+ },
+} as const;
+
+export const REVIEW_CYCLE_RULES: Record<string, Rule[]> = {
+ reviewCycleName: [{ required: true, message: '๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ์ ์
๋ ฅํ์ธ์.' }],
+ reviewees: [{ required: true, message: '๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํ์ธ์.' }],
+ questionTitle: [{ required: true, message: '์ง๋ฌธ ์ ๋ชฉ์ ์
๋ ฅํ์ธ์.' }],
+ questionDescription: [{ required: true, message: '์ง๋ฌธ ์ค๋ช
์ ์
๋ ฅํ์ธ์.' }],
+}; | TypeScript | ์๊ธฐ ์์๋ ๋ฐ๋ก ๋นผ์ ์ด์ ๊ฐ ๋ญ๊น์?
`Form.Item`์ `name` ์ธ์๋ ์ฌ์ฉ๋์ง ์๋ ๊ฒ ๊ฐ์๋ฐ `label`์ฒ๋ผ ๋ฐ๋ก ๋ฃ์ด๋ ์ข์๋ณด์ฌ์!
์๋๋ฉด label, name, rule์ ํ๋๋ก ๋ฌถ์ด๋ ์ข์ ๊ฒ ๊ฐ๊ตฌ์! ๊ฐ๋ณ๊ฒ ๋๋ ์๊ฐ ๋จ๊ฒจ๋ด
๋๋ค~ |
@@ -0,0 +1,90 @@
+import { API_PATH } from '@apis/constants';
+import { useQuery } from '@apis/common/useQuery';
+import { ReviewCycle } from './entities';
+import { ReviewCycleRequest, ReviewCycleResponse } from './type';
+import { useDelete, usePost, usePut } from '@apis/common/useMutation';
+import { get } from 'lodash';
+
+export function useGetReviewCycles() {
+ const {
+ data,
+ isLoading,
+ mutate: refetchReviewCycle,
+ } = useQuery<{ reviewCycles: ReviewCycle[] }>(API_PATH.REVIEW_CYCLES);
+
+ return {
+ reviewCycles: data?.reviewCycles,
+ isLoading,
+ refetchReviewCycle,
+ };
+}
+
+export function useCreateReviewCycle({
+ onSuccess,
+ onError,
+}: {
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePost<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: API_PATH.REVIEW_CYCLES,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ฑ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ createReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useUpdateReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId?: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePut<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: entityId ? `${API_PATH.REVIEW_CYCLES}/${entityId}` : null,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ updateReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useDeleteReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = useDelete({
+ endpoint: `${API_PATH.REVIEW_CYCLES}/${entityId}`,
+ onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์ญ์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ deleteReviewCycle: trigger,
+ isMutating,
+ };
+} | TypeScript | [์ง๋ฌธ]
`trigger`๋ฅผ ๋ฐ๋ก ๋๊ธฐ์ง ์๊ณ ํจ์๋ก ๋๊ฒจ์ฃผ๋ ์ด์ ๋ ํ์
์ ๊ณ ์ ์ํค๊ธฐ ์ํจ์ผ๊น์? |
@@ -0,0 +1,37 @@
+import useModal from 'hooks/useModal';
+import { Headline4 } from 'styles/typography';
+import ReviewCycleForm from '../ReviewCycleForm';
+import { message } from 'antd';
+import { useCreateReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+
+function useReviewCycleCreateModal() {
+ const modal = useModal();
+
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { createReviewCycle } = useCreateReviewCycle({
+ onSuccess: () => {
+ message.success('์๋ก์ด ๋ฆฌ๋ทฐ ์ ์ฑ
์ ์์ฑํ์ด์.');
+ modal.close();
+ refetchReviewCycle();
+ },
+ onError: message.error,
+ });
+
+ function render() {
+ return modal.render({
+ title: <Headline4>์๋ก์ด ๋ฆฌ๋ทฐ ์ ์ฑ
๋ง๋ค๊ธฐ</Headline4>,
+ visible: modal.visible,
+ children: (
+ <ReviewCycleForm onFinish={createReviewCycle} onReset={modal.close} confirmButtonProps={{ text: '์์ฑํ๊ธฐ' }} />
+ ),
+ });
+ }
+
+ return {
+ render,
+ open: modal.open,
+ close: modal.close,
+ };
+}
+
+export default useReviewCycleCreateModal; | Unknown | ์๋ฐ ์์ผ๋ก ๊ธฐ์กด `modal`์ ํ์ฅํ๋ ํ
์ผ๋ก ๋ง๋ค์ด๋ ์ข์ ๊ฒ ๊ฐ์์~
```suggestion
return {
...modal,
render,
};
``` |
@@ -0,0 +1,25 @@
+import { DeleteOutlined } from '@ant-design/icons';
+import { useDeleteReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+import { message } from 'antd';
+
+function DeleteButton({ entityId }: { entityId: number }) {
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { deleteReviewCycle } = useDeleteReviewCycle({
+ entityId,
+ onSuccess: refetchReviewCycle,
+ onError: message.error,
+ });
+
+ return (
+ <button
+ onClick={e => {
+ e.stopPropagation();
+ deleteReviewCycle();
+ }}
+ >
+ <DeleteOutlined />
+ </button>
+ );
+}
+
+export default DeleteButton; | Unknown | [์ง๋ฌธ]
`e.stopPropagation()`์ ์๋๊ฐ ๋ฌด์์ธ๊ฐ์? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.