HealthKit (16)
최근 이메일을 확인하다가 이전에 구입해둔 강의사이트가 24일을 마지막으로 폐쇄가 된다고 하면서, 이전에 구입해둔 강의를 다운받게 해준다고해서 들어가보니 이 강의의 iOS26 업데이트 부분이 새로 생겨서 정리를 해보려고 한다.
iOS 26 Update
우선 프로젝트 버전을 바꾸도록 한다.
그전에 이 포르젝트를 18.0으로 하고 빌드를 하여 warning이 있는것을 눌러서 recommend setting을 해주도록 한다.
이제 버전을 올려서 iOS26에서 새롭게 추가된 기능을 적용해보려 한다/
ContentUnavailableView 적용
현재는 아무런 데이터가 없을때 그냥 공백 그자체이다.
그래서 이부분에 이제는 유져에게 데이터가 없다는걸 알려줄 ContentUnavailableView를 적용해본다.
1
2
3
4
5
6
// HealthDataListView
.overlay(content: {
if listData.isEmpty {
ContentUnavailableView("No \(metric.title) to Display", systemImage: metric == .steps ? "figure.walk" : "figure")
}
})
이렇게 추가를 해준다.
그럼 이렇게 적용된걸 알 수 있다.
Chart 버그 수정
현재 Chart에 아무런 데이터가 없음에도 불구하고 이렇게 Avg Line이 그려진걸 알 수 있다. 이제 이부분도 수정을 하도록 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
// WeightLineChartView
// before
RuleMark(y: .value("Goal", 155))
.foregroundStyle(.mint)
.lineStyle(.init(lineWidth: 1, dash: [5]))
.accessibilityHidden(true
// after
if !chartData.isEmpty {
RuleMark(y: .value("Goal", 155))
.foregroundStyle(.mint)
.lineStyle(.init(lineWidth: 1, dash: [5]))
.accessibilityHidden(true)
}
이렇게 if를 통해 데이터가 있을때 line을 그려주도록 한다. (사진은 생략)
Mockdata 넣기
MockData를 넣기 위해
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// DashboardView
private func fetchHealthData() {
Task {
do {
await hkManager.addSimulatorData()
async let steps = hkManager.fetchStepCount()
async let weightsForLineChart = hkManager.fetchWeights(daysBack: 28)
async let weightsForDiffBarChart = hkManager.fetchWeights(daysBack: 29)
// 생략
}
// 생략
}
// 생략
}
이렇게 addSimulatorData 를 추가하여 값을 넣어준다.
Liquid Glass
Meet Liquid Glass는 wwdc2025에서 소개가 되었다.
우선 실행을 먼저 해보면 (그전에 iCloud 로그인이 되어 있어야함.)
이렇게 뜨는걸 알 수 있다.
여기 버튼 스타일을 이제 liquid glass를 적용해보려 한다.
1
2
// HealthKitPermissionPrimingView
.buttonStyle(.glassProminent)
그전에 이렇게 하면
이렇게 뜨는걸 알 수 있다. (왜냐면 지금은 잠시 iOS18로 해두었기 때문)
이럴땐 보통 available을 사용해서 버전마다 다르게 하는 방법이 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
if #available(iOS 26, *) {
Button("Connect Apple Health") {
isShowingHealthKitPermission = true
}
.buttonStyle(.glassProminent)
.tint(.pink)
} else {
Button("Connect Apple Health") {
isShowingHealthKitPermission = true
}
.buttonStyle(.borderedProminent)
.tint(.pink)
}
이렇게 해주면 iOS26이상일땐 Liquid Glass를 그 밑의 버전은 기존대로 유지가 된다.
CustomModifier 만들기
위에서 만든 available을 modifier로 바꿔서 코드를 좀 더 간략하게 바꿔본다.
새롭게 CustomModifier파일을 하나 만들어주고
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import SwiftUI
struct ProminentButton: ViewModifier {
var color: Color
func body(content: Content) -> some View {
if #available(iOS 26, *){
content
.buttonStyle(.glassProminent)
.tint(color)
} else {
content
.buttonStyle(.borderedProminent)
.tint(color)
}
}
}
extension View {
func prominentButton(color: Color) -> some View {
modifier(ProminentButton(color: color))
}
}
이렇게 Modifier 를 만들어준다.
이때 extension을 안쓰게 되면
1
.modifier(prominentButton(color: .pink))
이런식으로 써야해서 뭔가 modifier의 느낌이 잘 살지 않게된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// before
if #available(iOS 26, *) {
Button("Connect Apple Health") {
isShowingHealthKitPermission = true
}
.buttonStyle(.glassProminent)
.tint(.pink)
} else {
Button("Connect Apple Health") {
isShowingHealthKitPermission = true
}
.buttonStyle(.borderedProminent)
.tint(.pink)
}
// after
Button("Connect Apple Health") {
isShowingHealthKitPermission = true
}
.prominentButton(color: .pink)
이렇게 심플하게 된걸 알 수 있다.
다만 glassProminent 효과의 경우 확대해서 봐야 티가 날 정도라서 맥북에서 일반적인 시뮬레이터 크기로는 확인이 어렵다.
강의에선 Dark Mode에서는 더 잘보인다고 한다.
UI 수정
기존에 흰색 배경이던 DashboardView를 수정해본다.
1
2
3
4
5
6
7
// DashboardView
var backgroundColor: Color {
selectedStat == .steps ? .pink : .indigo
}
.navigationTitle("Dashboard")
.background(LinearGradient(colors: [backgroundColor.opacity(0.25), .clear], startPoint: .topLeading, endPoint: .bottomTrailing)) // new
그러면 이렇게 이제 분홍빛으로 바뀌게 된다.
weight는 인디고 컬러로 바뀌겠지만 사진은 생략.
이젠 차트 내부도 바꿔본다.
1
2
3
.background(RoundedRectangle(cornerRadius: 24, style: .continuous)
.stroke(.gray.opacity(0.5), lineWidth: 0.5)
.fill(Color(.secondarySystemBackground).gradient.opacity(0.5)))
이젠 그라데이션도 있으면서 달라진걸 알 수 있다.
그리고 수정하면서
1
2
3
4
5
6
7
8
9
10
11
12
13
// DashboardView
// before
}
.padding()
.task {
fetchHealthData()
}
// after
.padding()
}
.task {
fetchHealthData()
}
패딩의 위치를 올려주었는데.
저 줄의 차이가 보여준다.
그리고 DashBoardTitle의 경우는
.toolbarTitleDisplayMode(.inlineLarge)
사진을 봤을땐 좌상단에 딱 붙어있게 된다.
그리고 차트의 각진 부분도
1
.cornerRadius(3)
를 사용하면 모서리가 둥근느낌이 된다 (사진생략)
데이터 부분도 백그라운드를 줘보도록 한다.
코드는 위와 같고, 색상만 metric에 따라 바뀌도록 수정한다.
1
2
3
4
5
var backgroundColor: Color {
metric == .steps ? .pink : .indigo
}
.background(LinearGradient(colors: [backgroundColor.opacity(0.25), .clear], startPoint: .topLeading, endPoint: .bottomTrailing))
하지만 실행해 보면 색이 바뀌지 않는데, 그건 List 때문이다.
List는 내부적으로 UIKit의 스크롤 뷰(iOS 16부터는 UICollectionView, 이전에는 UITableView)를 기반으로 그려지고, 이 스크롤 영역은 자체적으로 불투명한 기본 배경색을 가지고 있다. .background()는 뷰의 뒤쪽에 레이어를 깔아주는 modifier라서, 그라데이션 자체는 정상적으로 적용되어 있지만 그 위를 List의 기본 배경이 덮고 있어 보이지 않는 것이다.
이때 iOS 16에서 추가된 .scrollContentBackground(.hidden)를 사용해준다.
1
2
3
4
5
List {
...
}
.scrollContentBackground(.hidden)
.background(LinearGradient(colors: [backgroundColor.opacity(0.25), .clear], startPoint: .topLeading, endPoint: .bottomTrailing))
List의 기본 배경이 숨겨지면서 뒤에 깔아둔 그라데이션이 보이게 된다.
다만 이건 List 전체의 배경만 숨기는 것이라 각 row의 배경(흰색 카드 부분)은 그대로 남는다. row까지 투명하게 하고 싶다면 row에 .listRowBackground(Color.clear)를 따로 주면 된다.
강의에서는
1
2
3
4
5
6
7
8
9
10
11
12
13
List(listData.reversed()) { data in
LabeledContent {
Text(data.value, format: .number.precision(.fractionLength(metric == .steps ? 0 : 1)))
} label: {
Text(data.date, format: .dateTime.month(.wide).day().year())
.accessibilityLabel(data.date.accesibilityDate)
}
.listRowBackground(Color(.secondarySystemBackground).opacity(0.35))
.accessibilityElement(children: .combine)
}
.navigationTitle(metric.title)
.scrollContentBackground(.hidden)
.background(LinearGradient(colors: [backgroundColor.opacity(0.25), .clear], startPoint: .topLeading, endPoint: .bottomTrailing))
secondaryBackground를 사용했다.
그러면 이제 Cell안에도 Background가 적용된걸 알 수 있다.
추가버튼 UI 수정하기
NavbarTint
기존에 이렇게 되어있던걸 수정해보려고 한다.
지금은 위에 보면 알겠지만 꽤나 빈공간이 많은걸 알 수 있다. 이제 이부분에 대해 공간낭비를 줄이면서 위에 dismiss, add data도 수정을 하려고 한다.
강의에서 언급하길 iOS26이후부터는 ToolBar에 Text보다는 간단한 Symbol로 연습을 하는게 좋다고 말을해서 버튼에 있는 Text도 Symbol로 같이 수정을 해보도록 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// DashboardView
var metricColor: Color {
selectedStat == .steps ? .pink : .indigo
}
var navbarTint: Color {
if #available(iOS 26, *) {
return .primary
} else {
return metricColor
}
}
.navigationTitle("Dashboard")
.toolbarTitleDisplayMode(.inlineLarge)
.background(LinearGradient(colors: [metricColor.opacity(0.25), .clear], startPoint: .topLeading, endPoint: .bottomTrailing))
.tint(navbarTint)
이렇게 코드를 구성해준다.
iOS 26부터는 툴바 버튼이 Liquid Glass 스타일로 바뀌면서 색을 입히기보다 기본 색을 유지하는 쪽이 자연스럽기 때문에, iOS 26 이상에서는 .primary를, 그 이전 버전에서는 metric 색상을 tint로 주도록 분기했다.
Toolbar
기존에 있던 Toolbar Modifier를 버전에따라 분기해준다.
1
2
3
4
5
6
7
8
9
10
11
12
13
.toolbar {
if #available(iOS 26, *) {
Button("Add Data", systemImage: "plus") {
isShowingAddData = true
}
.buttonStyle(.glassProminent)
.tint(metricColor)
} else {
Button("Add Data", systemImage: "plus") {
isShowingAddData = true
}
}
}
이렇게 하면
iOS26 에선 Liquid Glass 효과가 나온다 (이미지는 생략)
Sheet
현재는 sheet가 화면을 전부 차지하도록 올라오는데 우리가 이전에 구현한 sheet는 그리 큰 화면이 필요가 없기에 줄여보도록 한다.
1
2
3
4
.sheet(isPresented: $isShowingAddData) {
addDataView
.presentationDetents([.medium, .large])
}
간단하다. presentationDetents를 사용하면 된다.
.presentationDetents([.medium, .large])를 사용하면 아래와 같이 된다.
이때 사이즈를 더 조절하고 싶다면 아래와 같이 하면 된다.
.presentationDetents([.fraction(0.4)])
전체 height의 40% 만을 사용하겠다는 것이다.
그리고 강의에서는 sheet에도 .scrollContentBackground(.hidden)를 적용했다. iOS 26부터는 높이가 줄어든 sheet가 Liquid Glass 배경을 가지는데, Form의 기본 배경이 이를 덮기 때문에 숨겨주는 것이라고 한다.
다만 직접 실행해 봤을 때는 라이트 모드와 다크 모드 모두에서 넣었을 때와 뺐을 때의 차이를 거의 느끼지 못했다. 이 부분은 이유를 더 찾아보고 확인되면 추가하려고 한다.
그리고 addDataView에도 toolbar를 수정한다.
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
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
if #available(iOS 26, *){
Button(role: .confirm) {
addDataToHealthKit()
}
.tint(metricColor)
} else {
Button("Add Data") {
addDataToHealthKit()
}
}
}
ToolbarItem(placement: .topBarLeading) {
if #available(iOS 26, *) {
Button(role: .close) {
isShowingAddData = false
}
} else {
Button("Dismiss") {
isShowingAddData = false
}
}
}
}
그러면 아래와 같이 된다.
그런데 Sheet의 NavigationTitle이 너무 크게 나와서 이부분을 바꿔주는게 좋을듯해서
1
2
.navigationTitle(metric.title)
.navigationBarTitleDisplayMode(.inline)
이렇게 displaymode를 해주게 되면
이젠 Toolbar 사이에 나오는걸 알 수 있다.
matchedTransitionSource
iOS 26의 기본 앱들(메일의 새 메일 작성 등)을 보면 툴바 버튼을 눌렀을 때 버튼에서 sheet가 쭉 늘어나듯 열리는 애니메이션이 있다. 이걸 zoom 전환이라고 하는데, 우리 앱의 Add Data 버튼에도 적용해 보려고 한다.
zoom 전환은 세 가지로 구성된다.
@Namespace로 이름 공간을 만든다.- 출발점(source)에
matchedTransitionSource(id:in:)를 붙인다. - 도착점(destination)에
navigationTransition(.zoom(sourceID:in:))을 붙인다.
여기서 @Namespace는 “어떤 뷰와 어떤 뷰가 짝인지”를 SwiftUI가 알 수 있게 해주는 일종의 그룹 이름이다. 출발점과 도착점에 같은 id("addData")와 같은 namespace(zoomTransition)를 넘겨주면 SwiftUI가 둘을 짝으로 인식하고, 그 사이를 이어주는 애니메이션을 만들어 준다. id만 같고 namespace가 다르면 서로 다른 그룹으로 취급되어 연결되지 않는다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Namespace var zoomTransition
.overlay(content: {
// 생략
})
.toolbar {
if #available(iOS 26, *) {
ToolbarItem {
Button("Add Data", systemImage: "plus") {
isShowingAddData = true
}
.buttonStyle(.glassProminent)
.tint(metricColor)
}
.matchedTransitionSource(id: "addData", in: zoomTransition)
} else {
ToolbarItem {
Button("Add Data", systemImage: "plus") {
isShowingAddData = true
}
}
}
}
matchedTransitionSource는 iOS 18부터 있었지만, 그때는 일반 View에만 붙일 수 있었다. 툴바 안의 버튼은 우리가 만든 View가 아니라 시스템이 툴바 아이템으로 다시 그려주기 때문에, Button에 붙여도 출발점으로 인식되지 않는다. iOS 26부터 툴바 아이템(ToolbarItem)에 직접 붙일 수 있는 버전이 추가되었기 때문에, Button이 아니라 ToolbarItem으로 감싼 뒤 거기에 붙여줘야 한다.
그리고 sheet도
1
2
3
4
5
6
7
8
9
10
11
.sheet(isPresented: $isShowingAddData) {
if #available(iOS 26, *) {
addDataView
.presentationDetents([.fraction(0.4)])
.scrollContentBackground(.hidden)
.navigationTransition(.zoom(sourceID: "addData", in: zoomTransition))
} else {
addDataView
.presentationDetents([.fraction(0.4)])
}
}
이렇게 버전에 따라 다르게 해준다. navigationTransition(.zoom) 자체는 iOS 18부터 쓸 수 있지만, 출발점인 툴바 아이템 쪽이 iOS 26부터만 지정 가능하기 때문에 도착점도 iOS 26에서만 적용되도록 맞춰주었다.
실행하면
Add Data 버튼에서 sheet가 늘어나듯 열리고, 닫을 때는 다시 버튼 쪽으로 줄어들며 들어가는 것을 볼 수 있다.
참고
Get to know the new design system
Build a SwiftUI app with the new design
Github: Step-Tracker Repository
























