포스트

Todoey (10)

Cell에 Color추가하기

카멜레온사이트를 이용하여 Library를 가져온다.

pod install을 통해 library 설치 완료.

참고

해당 library는 현재 나와있는대로 설치를 하면 이전 버전의 swift로 작성된것이라 에러가 많이 뜬다. pod ‘ChameleonFramework/Swift’, :git => ‘https://github.com/wowansm/Chameleon’, :branch => ‘swift5’

이걸로 설치하도록 하자.

1
2
3
4
5
6
7
8
9
10
11
import ChameleonFramework

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = super.tableView(tableView, cellForRowAt: indexPath)
        
        cell.textLabel?.text = categories?[indexPath.row].name ?? "No Categories added Yet"
        cell.backgroundColor = UIColor.randomFlat() // new
        
        return cell
    }

simulator_screenshot_B8423333-9EC8-4336-A35A-B42577B695A9

색상이 아주 잘 나온다.

특이점이라면, 위의 코드를 보면 알겠지만 랜덤으로 색상이 결정된다. 즉 실행할때마다 임의의 색상이 나온다는것.

Cell 색상 고정하기.

print(UIColor.randomFlat().hexValue()) 를 사용하면 셀 색깔에 대한 hex값을 얻을 수 있다.

이걸 이용해서 색상을 저장하여 사용 하면 될것같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Category: Object {
    
    @objc dynamic var name: String = ""
    @objc dynamic var color: String = "" // new
    let items = List<Item>() 
    
}

@IBAction func buttonPressed(_ sender: UIBarButtonItem) {
        
        var textField = UITextField()
        
        let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert)
        
        let action = UIAlertAction(title: "Add Item", style: .default) { (action) in
            
            let newCategory = Category()
            newCategory.name = textField.text!
            newCategory.color = UIColor.randomFlat().hexValue() // new
            
            self.save(category: newCategory)
            
        }
        
        alert.addTextField { (alertTextField) in
            alertTextField.placeholder = "Add a new Category"
            textField = alertTextField
        }
        
        alert.addAction(action)
        
        present(alert, animated: true, completion: nil)
        
        tableView.reloadData()
        
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = super.tableView(tableView, cellForRowAt: indexPath)
        
        cell.textLabel?.text = categories?[indexPath.row].name ?? "No Categories added Yet"
        cell.backgroundColor = UIColor(hexString: realm.objects(Category.self)[indexPath.row].color) // new
        print(UIColor.randomFlat().hexValue())
        
        return cell
    }    

우선 나는 이렇게 했는데

1
2
3
4
5
// 나
cell.backgroundColor = UIColor(hexString: realm.objects(Category.self)[indexPath.row].color)

// 강의
cell.backgroundColor = UIColor(hexString: categories?[indexPath.row].color ?? "1D98F6")

이렇게 했다.

Gradient Flow Cell 만들기.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = super.tableView(tableView, cellForRowAt: indexPath)
        
        if let item = todoItems?[indexPath.row] {
            cell.textLabel?.text = item.title
            
            if let color = FlatSkyBlue().darken(byPercentage:                                                CGFloat(indexPath.row / todoItems!.count)) {
                
                cell.backgroundColor = color
                
            }
            
            
            cell.accessoryType = item.done ? .checkmark : .none
        } else {
            cell.textLabel?.text = "No Items Added"
        }
        
        return cell
    }

Library의 darken을 이용하여 그라데이션 효과를 주려고 한다.

CGFloat(indexPath.row / todoItems!.count) 아래로 내려갈수록 색을 더 진하게 한다는 의미.

simulator_screenshot_CF49B080-48BC-4441-A9DC-60F99BF2B4B0

그런데 실행해보니 변화가 없다?

print(indexPath.row / todoItems!.count) 를 찍어보니 0 이 나와버린다.

왜냐면 나눌때 int기준으로 나누고 CGFloat으로 타입이 변환되기때문이다.

print안에 두 값은 Int이기에 해당 값을 CGFloat으로 타입변환을 해주고 나면 원하는 값이 나오게 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = super.tableView(tableView, cellForRowAt: indexPath)
        
        if let item = todoItems?[indexPath.row] {
            cell.textLabel?.text = item.title
            
            if let color = FlatSkyBlue().darken(byPercentage:                                                CGFloat(CGFloat(indexPath.row) / CGFloat(todoItems!.count))) {
                
                cell.backgroundColor = color
                
            }

            
            cell.accessoryType = item.done ? .checkmark : .none
        } else {
            cell.textLabel?.text = "No Items Added"
        }
        
        return cell
    }

simulator_screenshot_014C4CBA-61EE-4E12-9D28-90ABCCD05B2E

그라데이션 효과는 이제 구현이 되었다.

하지만 가장 마지막의 셀의 경우 너무 어두워서 점점 black과 가까워진다.

이말은 cell의 text가 보이지않게된다는것.

유져입장에서는 이부분 또한 하나의 컴플레인으로 작용할 수 있는 요소이기에 해당부분을 수정해보도록 하자.

Readme의 ConstrastColor를 사용하여 text의 색을 주었다.

cell.textLabel?.textColor = ContrastColorOf(color, returnFlat: true)

simulator_screenshot_6B8DDA7D-63F1-401A-8A26-D6BF71E23DBD

Category의 색을 넘겨받아 TodoListTable에 반영하기

1
2
3
4
5
if let color = UIColor(hexString: selectedCategory!.color)?.darken(byPercentage:                                                CGFloat(CGFloat(indexPath.row) / CGFloat(todoItems!.count))) { // modified
                
                cell.backgroundColor = color
                cell.textLabel?.textColor = ContrastColorOf(color, returnFlat: true)
            }
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.