본문 바로가기
FE 공부/Swift

Swift - TableView _ Managing Selection

by 꼬질꼬질두부 2022. 11. 29.

Handling row selection in a table view

Detect when a user taps a table view cell so your app can take the next indicated action.
: 테이블뷰 row가 탭되면 화면에서 action을 취함(체크 마킹 등)

 

 

Configure row selection behavior

 

selection 설정에서 No Selection / Single Selection / Multiple Selection 지정 가능

 

 

 

< 사용자가 row를 선택할 수 있는지 여부를 결정하는 부울 값 >

 

var allowsSelection: Bool { get set }

 

< 다중 선택 여부 부울 값 >

In macOS, when the value of this property is true, the user can select additional rows by holding the Command or Shift key while clicking on the additional rows they want to select. If the user isn’t holding a modifier key, clicking on another row clears the current selection and selects only the clicked row. 

: 사용자는 Command 또는 Shift 키를 누른 상태에서 선택하려는 추가 row을 클릭하여 선택할 수 있습니다. 

사용자가 수정자 키를 누르고 있지 않은 경우 다른 row을 클릭하면 현재 선택이 지워지고 클릭된 row만 선택됩니다.

var allowsMultipleSelection: Bool { get set }

 

< editing mode시 선택 여부 부울 값 > 

var allowsSelectionDuringEditing: Bool { get set }

 

 

< editing mode시 다중 선택 가능 여부​​ 부울 값 >

var allowsMultipleSelectionDuringEditing: Bool { get set }

 


Manage selection lists

선택됐을 때 이벤트를 수행하려면

tableView(_:didSelectRowAt:) 사용

optional func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
	code
}

 

선택을 해제하려면 deselectRow(at:animated:) 사용

func deselectRow(at indexPath: IndexPath, animated: Bool)

 

예제 코드

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    // 선택 취소 후 체크 박스에 상태 표시
    tableView.deselectRow(at: indexPath, animated: false)
    
    guard let cell = tableView.cellForRow(at: indexPath) else { return }
    
    // 선택된 항목을 업데이트하여 사용자가 짐을 챙겼는지 여부를 나타냅니다.
    let item = packingList[indexPath.row]
    let newItem = PackingItem(name: item.name, isPacked: !item.isPacked)
    packingList.remove(at: indexPath.row)
    packingList.insert(newItem, at: indexPath.row)
    
    // 체크 마크 보여주는 과정
    if newItem.isPacked {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }
}

 


  • shouldHighlightRowAt: highlight 여부 설정
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        //첫번째 cell에만 효과 미적용
        return indexPath.row != 0
    }
  • tableView(_ tableView:didHighlightRowAt indexPath:) : highlight된 후 호출
  • tableView(_ tableView:didUnhighlightRowAt indexPath: ): highlight가 사라진 후 호출

'FE 공부 > Swift' 카테고리의 다른 글

변수와 자료형  (0) 2023.03.11
Swift - TableView _ Edit Mode  (0) 2022.11.29
Swift - TableView Section  (0) 2022.11.22
Swift - Alert Controller  (0) 2022.11.22
Swift _ StackView  (0) 2022.11.15

댓글