[TIL] 09.06

Junyoung_Hong·2023년 9월 6일
0

TIL_9월

목록 보기
5/19
post-thumbnail

1. 코드로 Color 만들기

색상을 asset으로 만들기도 하지만, extension으로 만들어서 사용하기도 한다. rgb값을 입력할 때, 꼭 /255 를 같이 입력해주어야 한다. 또한 투명도를 나타내는 alpha값은 0부터 1까지이다.

extension UIColor {
    static let mainColor = UIColor(
        red: 236/255, green: 33/255, blue: 35/255, alpha: 1
    )
}

2. 버튼 target 바꾸기

버튼에 addTarget을 주어서 함수를 입력한다. 같은 버튼에 여러가지 함수를 주기 위해서는 기존의 Target을 제거하고, 새로 추가해야 한다.

self.startButton.removeTarget(self, action: #selector(self.profileButtonPressed), for: .touchUpInside)
self.startButton.addTarget(self, action: #selector(self.moveBackMyPage), for: .touchUpInside)

이렇게 제거를 하지 않고 addTarget을 하게되면, 기존의 #selector 함수가 호출된다.

3. CollectionView Cell 클릭 시, 화면 이동

보통 화면 전환을 구현할 때, navigation이나 present를 사용할 것이다. 그런데 둘 다 UIViewController에서 사용할 수 있다. 필자의 경우 TableViewCell안에 CollectionView가 들어가 있고, CollectionView의 Cell을 클릭했을 때, 화면이동이 되게 하고 싶었다. 이를 위해 Delegate를 사용했다.
프로토콜은 상속에 의해 멀리 떨어져 있는 두 클래스가 특정 목표를 달성하기 위해 서로 통신할 수 있도록 한다고 되어있다. 즉, CollectionViewCell 클래스에서 처리하기 곤란한 화면 이동 방법을 ViewController 클래스에 위임(delegate)해주면 된다.

3-1. Protocol 만들어주기

우선 CollectionView를 넣은 TableViewCell에 Protocol을 만들어주자.

// Delegate Pattern을 위한 Protocol 생성
protocol RecordTableViewCellDelegate: AnyObject {
    func didTapRecordCollectionViewCell()
}

class RecordTableViewCell: UITableViewCell {
}

그 다음, Delegate 타입의 변수를 선언해준다.

weak var recordTableViewCellDelegate: RecordTableViewCellDelegate?

3-2. CollectionViewCell 클릭 함수 사용

func collectionView( ... didSelectItemAt) 를 사용해서 CollectionViewCell이 눌렀을 때, protocol에서 만들어놓은 함수를 사용되도록 하자.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let recordTableViewCellDelegate = recordTableViewCellDelegate {
        recordTableViewCellDelegate.didTapRecordCollectionViewCell()
    }
}

3-3. ViewController에서 메서드 구현하기

이제 protocol에서 만들었던 함수에 화면이동 기능을 추가하자.

extension MyPageViewController: RecordTableViewCellDelegate {
    
    func didTapRecordCollectionViewCell() {
        navigationController?.pushViewController(videoDetailVC, animated: true)
    }
}

3-4. 대리자 설정

ViewController가 대리자 역할을 하고 있기 때문에 ViewController가 대리자임을 알려주어야 한다.

extension MyPageViewController: UITableViewDelegate, UITableViewDataSource {

    // TableView의 각 줄
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

		.
        .
        .
        
        else if indexPath.row == 1 {
            guard let recordTableViewCell = tableView.dequeueReusableCell(withIdentifier: RecordTableViewCell.identifier, for: indexPath) as? RecordTableViewCell else {
                return UITableViewCell()
            }
            recordTableViewCell.selectionStyle = .none
            recordTableViewCell.recordTableViewCellDelegate = self
            return recordTableViewCell
        }
        
        .
        .
        .
    }
}
profile
iOS 개발자를 향해 성장 중

0개의 댓글