Files
XRLib/Assets/Sample/UIToolkit/UTKStyleGuideSample.Modal.cs
2026-02-24 20:01:56 +09:00

1227 lines
40 KiB
C#

#nullable enable
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UIElements;
using UVC.UIToolkit;
/// <summary>
/// UTKStyleGuideSample의 Modal, Tab, Picker 카테고리 Initialize 메서드들
/// </summary>
public partial class UTKStyleGuideSample
{
#region Tab Initializer
private void InitializeTabViewSample(VisualElement root)
{
// Top Alignment (기본)
var tabContainerTop = root.Q<VisualElement>("tabview-top-container");
if (tabContainerTop != null)
{
var tabView = new UTKTabView();
tabView.Align = TabAlign.Top;
tabView.style.width = 500;
tabView.style.height = 200;
tabView.AddUTKTab("일반", new Label("일반 설정 내용입니다.\n탭이 위쪽에 배치됩니다."));
tabView.AddUTKTab("고급", new Label("고급 설정 내용입니다."));
tabView.AddUTKTab("정보", new Label("정보 탭 내용입니다."));
tabContainerTop.Add(tabView);
}
// Bottom Alignment
var tabContainerBottom = root.Q<VisualElement>("tabview-bottom-container");
if (tabContainerBottom != null)
{
var tabView = new UTKTabView();
tabView.Align = TabAlign.Bottom;
tabView.style.width = 500;
tabView.style.height = 200;
tabView.AddUTKTab("일반", new Label("일반 설정 내용입니다.\n탭이 아래쪽에 배치됩니다."));
tabView.AddUTKTab("고급", new Label("고급 설정 내용입니다."));
tabView.AddUTKTab("정보", new Label("정보 탭 내용입니다."));
tabContainerBottom.Add(tabView);
}
// Left Alignment
var tabContainerLeft = root.Q<VisualElement>("tabview-left-container");
if (tabContainerLeft != null)
{
var tabView = new UTKTabView();
tabView.Align = TabAlign.Left;
tabView.style.width = 500;
tabView.style.height = 200;
tabView.AddUTKTab("일반", new Label("일반 설정 내용입니다.\n탭이 왼쪽에 세로로 배치됩니다."));
tabView.AddUTKTab("고급", new Label("고급 설정 내용입니다."));
tabView.AddUTKTab("정보", new Label("정보 탭 내용입니다."));
tabContainerLeft.Add(tabView);
}
// Right Alignment
var tabContainerRight = root.Q<VisualElement>("tabview-right-container");
if (tabContainerRight != null)
{
var tabView = new UTKTabView();
tabView.Align = TabAlign.Right;
tabView.style.width = 500;
tabView.style.height = 200;
tabView.AddUTKTab("일반", new Label("일반 설정 내용입니다.\n탭이 오른쪽에 세로로 배치됩니다."));
tabView.AddUTKTab("고급", new Label("고급 설정 내용입니다."));
tabView.AddUTKTab("정보", new Label("정보 탭 내용입니다."));
tabContainerRight.Add(tabView);
}
SetCodeSamples(root,
csharpCode: @"// 기본 사용법 (Top Alignment)
var tabView = new UTKTabView();
tabView.Align = TabAlign.Top; // 기본값
tabView.style.width = 500;
tabView.style.height = 200;
// 탭 추가
tabView.AddUTKTab(""일반"", new Label(""일반 설정 내용""));
tabView.AddUTKTab(""고급"", new Label(""고급 설정 내용""));
tabView.AddUTKTab(""정보"", new Label(""정보 탭 내용""));
// Bottom Alignment - 탭이 아래쪽에 배치
var tabViewBottom = new UTKTabView();
tabViewBottom.Align = TabAlign.Bottom;
tabViewBottom.AddUTKTab(""Tab 1"", new Label(""Content 1""));
// Left Alignment - 탭이 왼쪽에 세로로 배치
var tabViewLeft = new UTKTabView();
tabViewLeft.Align = TabAlign.Left;
tabViewLeft.AddUTKTab(""Tab 1"", new Label(""Content 1""));
// Right Alignment - 탭이 오른쪽에 세로로 배치
var tabViewRight = new UTKTabView();
tabViewRight.Align = TabAlign.Right;
tabViewRight.AddUTKTab(""Tab 1"", new Label(""Content 1""));
// 복잡한 콘텐츠 추가
var contentContainer = new VisualElement();
contentContainer.Add(new Label(""복잡한 콘텐츠""));
contentContainer.Add(new UTKButton(""버튼""));
tabView.AddUTKTab(""Tab 4"", contentContainer);
// 탭 변경 이벤트
tabView.OnTabChanged += (index, tab) =>
{
Debug.Log($""선택된 탭 인덱스: {index}"");
};
// 프로그램으로 탭 선택
tabView.SelectedIndex = 1; // 두 번째 탭 선택
// 현재 선택된 탭 인덱스
var currentTab = tabView.SelectedIndex;",
uxmlCode: @"<!-- 네임스페이스 선언 -->
<ui:UXML xmlns:utk=""UVC.UIToolkit"">
<!-- Top Alignment (기본값) -->
<utk:UTKTabView align=""Top"" style=""width: 500px; height: 200px;"">
<utk:UTKTab label=""일반"">
<ui:Label text=""일반 설정 내용"" />
</utk:UTKTab>
<utk:UTKTab label=""고급"">
<ui:Label text=""고급 설정 내용"" />
</utk:UTKTab>
</utk:UTKTabView>
<!-- Bottom Alignment - 탭이 아래쪽 -->
<utk:UTKTabView align=""Bottom"" style=""width: 500px; height: 200px;"">
<utk:UTKTab label=""Tab 1"">
<ui:Label text=""Content 1"" />
</utk:UTKTab>
<utk:UTKTab label=""Tab 2"">
<ui:Label text=""Content 2"" />
</utk:UTKTab>
</utk:UTKTabView>
<!-- Left Alignment - 탭이 왼쪽 (세로) -->
<utk:UTKTabView align=""Left"" style=""width: 500px; height: 200px;"">
<utk:UTKTab label=""Tab 1"">
<ui:Label text=""Content 1"" />
</utk:UTKTab>
<utk:UTKTab label=""Tab 2"">
<ui:Label text=""Content 2"" />
</utk:UTKTab>
</utk:UTKTabView>
<!-- Right Alignment - 탭이 오른쪽 (세로) -->
<utk:UTKTabView align=""Right"" style=""width: 500px; height: 200px;"">
<utk:UTKTab label=""Tab 1"">
<ui:Label text=""Content 1"" />
</utk:UTKTab>
<utk:UTKTab label=""Tab 2"">
<ui:Label text=""Content 2"" />
</utk:UTKTab>
</utk:UTKTabView>
<!-- 동적 생성도 권장 -->
<utk:UTKTabView name=""tab-view-1"" align=""Top"" />
</ui:UXML>");
}
#endregion
#region Modal Initializers
private void InitializeAlertSample(VisualElement root)
{
if (_root == null) return;
UTKAlert.SetRoot(_root);
var btnInfo = root.Q<UTKButton>("btn-info");
btnInfo?.RegisterCallback<ClickEvent>(_ => ShowInfoAlertAsync().Forget());
var btnSuccess = root.Q<UTKButton>("btn-success");
btnSuccess?.RegisterCallback<ClickEvent>(_ => ShowSuccessAlertAsync().Forget());
var btnWarning = root.Q<UTKButton>("btn-warning");
btnWarning?.RegisterCallback<ClickEvent>(_ => ShowWarningAlertAsync().Forget());
var btnError = root.Q<UTKButton>("btn-error");
btnError?.RegisterCallback<ClickEvent>(_ => ShowErrorAlertAsync().Forget());
var btnConfirm = root.Q<UTKButton>("btn-confirm");
btnConfirm?.RegisterCallback<ClickEvent>(_ => ShowConfirmAlertAsync().Forget());
var btnConfirmCustom = root.Q<UTKButton>("btn-confirm-custom");
btnConfirmCustom?.RegisterCallback<ClickEvent>(_ => ShowConfirmCustomLabelsAsync().Forget());
var btnCallback = root.Q<UTKButton>("btn-callback");
btnCallback?.RegisterCallback<ClickEvent>(_ =>
{
UTKAlert.ShowInfo("Callback Style", "This uses callback instead of async.",
onClose: () => Debug.Log("Alert closed via callback"));
});
var btnConfirmCallback = root.Q<UTKButton>("btn-confirm-callback");
btnConfirmCallback?.RegisterCallback<ClickEvent>(_ =>
{
UTKAlert.ShowConfirm("Confirm", "Do you want to proceed?",
onConfirm: () => Debug.Log("Confirmed via callback!"),
onCancel: () => Debug.Log("Cancelled via callback!"));
});
SetCodeSamples(root,
csharpCode: @"// Root 설정 (한 번만)
UTKAlert.SetRoot(rootVisualElement);
// ========================================
// 1. Async/Await 방식 (권장)
// ========================================
// Info Alert
await UTKAlert.ShowInfoAsync(""정보"", ""이것은 정보 메시지입니다."");
// Success Alert
await UTKAlert.ShowSuccessAsync(""성공"", ""작업이 성공적으로 완료되었습니다!"");
// Warning Alert
await UTKAlert.ShowWarningAsync(""경고"", ""주의가 필요합니다."");
// Error Alert
await UTKAlert.ShowErrorAsync(""오류"", ""오류가 발생했습니다!"");
// Confirm Dialog
bool result = await UTKAlert.ShowConfirmAsync(""확인"", ""정말 진행하시겠습니까?"");
if (result)
{
Debug.Log(""사용자가 확인을 눌렀습니다."");
}
else
{
Debug.Log(""사용자가 취소를 눌렀습니다."");
}
// Confirm with Custom Labels
bool deleteResult = await UTKAlert.ShowConfirmAsync(
""항목 삭제"",
""이 항목을 정말 삭제하시겠습니까?"",
confirmLabel: ""삭제"",
cancelLabel: ""유지""
);
// closeOnBlockerClick 옵션 (배경 클릭 시 닫기)
await UTKAlert.ShowInfoAsync(""정보"", ""배경을 클릭해도 닫힙니다."", closeOnBlockerClick: true);
// ========================================
// 2. Callback 방식
// ========================================
// Info with Callback
UTKAlert.ShowInfo(""정보"", ""콜백 방식입니다."",
onClose: () => Debug.Log(""Alert가 닫혔습니다.""));
// Confirm with Callback
UTKAlert.ShowConfirm(""확인"", ""진행하시겠습니까?"",
onConfirm: () => Debug.Log(""확인 클릭!""),
onCancel: () => Debug.Log(""취소 클릭!""));");
}
private async UniTaskVoid ShowInfoAlertAsync()
{
await UTKAlert.ShowInfoAsync("Information", "This is an info message.");
Debug.Log("Info alert closed");
}
private async UniTaskVoid ShowSuccessAlertAsync()
{
await UTKAlert.ShowSuccessAsync("Success", "Operation completed successfully!", closeOnBlockerClick: true);
Debug.Log("Success alert closed");
}
private async UniTaskVoid ShowWarningAlertAsync()
{
await UTKAlert.ShowWarningAsync("Warning", "This is a warning message.");
Debug.Log("Warning alert closed");
}
private async UniTaskVoid ShowErrorAlertAsync()
{
await UTKAlert.ShowErrorAsync("Error", "An error has occurred!");
Debug.Log("Error alert closed");
}
private async UniTaskVoid ShowConfirmAlertAsync()
{
bool result = await UTKAlert.ShowConfirmAsync("Confirm", "Are you sure?");
Debug.Log(result ? "Confirmed!" : "Cancelled!");
}
private async UniTaskVoid ShowConfirmCustomLabelsAsync()
{
bool result = await UTKAlert.ShowConfirmAsync("Delete Item", "Are you sure you want to delete this item?",
confirmLabel: "Delete", cancelLabel: "Keep");
Debug.Log(result ? "Item deleted!" : "Item kept!");
}
private void InitializeToastSample(VisualElement root)
{
var btnInfo = root.Q<UTKButton>("btn-toast-info");
btnInfo?.RegisterCallback<ClickEvent>(_ => UTKToast.Show("This is an info toast!"));
var btnSuccess = root.Q<UTKButton>("btn-toast-success");
btnSuccess?.RegisterCallback<ClickEvent>(_ => UTKToast.ShowSuccess("Operation successful!"));
var btnWarning = root.Q<UTKButton>("btn-toast-warning");
btnWarning?.RegisterCallback<ClickEvent>(_ => UTKToast.ShowWarning("Warning: Check your input!"));
var btnError = root.Q<UTKButton>("btn-toast-error");
btnError?.RegisterCallback<ClickEvent>(_ => UTKToast.ShowError("An error occurred!"));
SetCodeSamples(root,
csharpCode: @"// Root 설정 (한 번만)
UTKToast.SetRoot(rootVisualElement);
// Info Toast (기본)
UTKToast.Show(""이것은 정보 토스트입니다!"");
// Success Toast
UTKToast.ShowSuccess(""작업이 성공적으로 완료되었습니다!"");
// Warning Toast
UTKToast.ShowWarning(""경고: 입력값을 확인하세요!"");
// Error Toast
UTKToast.ShowError(""오류가 발생했습니다!"");
// 지속 시간 설정 (밀리초)
UTKToast.Show(""5초 동안 표시"", 5000);
// 사용 예시
public async UniTask SaveDataAsync()
{
try
{
await SaveToServerAsync();
UTKToast.ShowSuccess(""데이터가 저장되었습니다."");
}
catch (Exception ex)
{
UTKToast.ShowError($""저장 실패: {ex.Message}"");
}
}");
}
private void InitializeTooltipSample(VisualElement root)
{
var btnShort = root.Q<UTKButton>("btn-short-tooltip");
if (btnShort != null)
{
UTKTooltipManager.Instance.AttachTooltip(btnShort, "This is a short tooltip.");
}
var btnLong = root.Q<UTKButton>("btn-long-tooltip");
if (btnLong != null)
{
UTKTooltipManager.Instance.AttachTooltip(btnLong, "This is a longer tooltip message that demonstrates how the tooltip handles multiple lines of text content.");
}
SetCodeSamples(root,
csharpCode: @"// 1. 버튼에 툴팁 연결
var saveButton = new UTKButton("""", UTKMaterialIcons.Save);
UTKTooltipManager.Instance.AttachTooltip(saveButton, ""저장 (Ctrl+S)"");
// 2. 다국어 키로 툴팁 연결
UTKTooltipManager.Instance.AttachTooltip(settingsButton, ""tooltip_settings"");
// 4. 아이콘 버튼에 툴팁
var deleteBtn = new UTKButton("""", UTKMaterialIcons.Delete) { IconOnly = true };
UTKTooltipManager.Instance.AttachTooltip(deleteBtn, ""삭제"");
// 5. 툴팁 업데이트
UTKTooltipManager.Instance.UpdateTooltip(button, ""새로운 설명"");
// 6. 툴팁 제거
UTKTooltipManager.Instance.DetachTooltip(button);
// 7. 즉시 표시 (특정 위치에)
UTKTooltipManager.Instance.Show(""임시 정보"", new Vector2(100, 200));
// 8. 숨기기
UTKTooltipManager.Instance.Hide();
// 9. 여러 요소에 툴팁 연결
var buttons = new[] { btn1, btn2, btn3 };
var tooltips = new[] { ""버튼 1"", ""버튼 2"", ""버튼 3"" };
for (int i = 0; i < buttons.Length; i++)
{
UTKTooltipManager.Instance.AttachTooltip(buttons[i], tooltips[i]);
}");
}
#endregion
#region Modal Initializers (UTKModal)
private void InitializeModalSample(VisualElement root)
{
if (_root == null) return;
UTKModal.SetRoot(_root);
// Modal Sizes
var btnSmall = root.Q<UTKButton>("btn-modal-small");
btnSmall?.RegisterCallback<ClickEvent>(_ => ShowModalWithSize(UTKModal.ModalSize.Small));
var btnMedium = root.Q<UTKButton>("btn-modal-medium");
btnMedium?.RegisterCallback<ClickEvent>(_ => ShowModalWithSize(UTKModal.ModalSize.Medium));
var btnLarge = root.Q<UTKButton>("btn-modal-large");
btnLarge?.RegisterCallback<ClickEvent>(_ => ShowModalWithSize(UTKModal.ModalSize.Large));
var btnFullScreen = root.Q<UTKButton>("btn-modal-fullscreen");
btnFullScreen?.RegisterCallback<ClickEvent>(_ => ShowModalWithSize(UTKModal.ModalSize.FullScreen));
// Options
var btnFooter = root.Q<UTKButton>("btn-modal-footer");
btnFooter?.RegisterCallback<ClickEvent>(_ =>
{
var modal = UTKModal.Create("푸터 버튼 모달", UTKModal.ModalSize.Medium);
modal.Add(new Label("확인 또는 취소를 선택하세요."));
var confirmBtn = new UTKButton("확인") { Variant = UTKButton.ButtonVariant.Primary };
confirmBtn.RegisterCallback<ClickEvent>(_ =>
{
Debug.Log("Modal confirmed");
modal.Close();
});
var cancelBtn = new UTKButton("취소") { Variant = UTKButton.ButtonVariant.Normal };
cancelBtn.RegisterCallback<ClickEvent>(_ =>
{
Debug.Log("Modal cancelled");
modal.Close();
});
modal.AddToFooter(cancelBtn);
modal.AddToFooter(confirmBtn);
modal.Show();
});
var btnNoClose = root.Q<UTKButton>("btn-modal-no-close");
btnNoClose?.RegisterCallback<ClickEvent>(_ =>
{
var modal = UTKModal.Create("닫기 버튼 없음", UTKModal.ModalSize.Small);
modal.ShowCloseButton = false;
modal.CloseOnBackdropClick = true;
modal.Add(new Label("닫기 버튼이 없습니다.\n배경을 클릭하면 닫힙니다."));
modal.Show();
});
var btnNoBackdrop = root.Q<UTKButton>("btn-modal-no-backdrop");
btnNoBackdrop?.RegisterCallback<ClickEvent>(_ =>
{
var modal = UTKModal.Create("배경 클릭 비활성화", UTKModal.ModalSize.Small);
modal.CloseOnBackdropClick = false;
modal.Add(new Label("배경을 클릭해도 닫히지 않습니다.\nX 버튼으로만 닫을 수 있습니다."));
modal.Show();
});
// Custom Content - Form Modal
var btnForm = root.Q<UTKButton>("btn-modal-form");
btnForm?.RegisterCallback<ClickEvent>(_ =>
{
var modal = UTKModal.Create("사용자 정보 입력", UTKModal.ModalSize.Medium);
var nameField = new UTKInputField("이름");
var emailField = new UTKInputField("이메일");
modal.Add(nameField);
modal.Add(emailField);
var submitBtn = new UTKButton("제출") { Variant = UTKButton.ButtonVariant.Primary };
submitBtn.RegisterCallback<ClickEvent>(_ =>
{
Debug.Log($"Name: {nameField.value}, Email: {emailField.value}");
modal.Close();
});
var cancelBtn = new UTKButton("취소") { Variant = UTKButton.ButtonVariant.Normal };
cancelBtn.RegisterCallback<ClickEvent>(_ => modal.Close());
modal.AddToFooter(cancelBtn);
modal.AddToFooter(submitBtn);
modal.Show();
});
SetCodeSamples(root,
csharpCode: @"// Root 설정 (한 번만)
UTKModal.SetRoot(rootVisualElement);
// ========================================
// 1. 기본 모달 표시
// ========================================
var modal = UTKModal.Create(""제목"", UTKModal.ModalSize.Medium);
modal.Add(new Label(""모달 내용""));
// 닫힘 이벤트
modal.OnClosed += () => Debug.Log(""모달 닫힘"");
// 화면에 표시
modal.Show();
// ========================================
// 2. 모달 크기
// ========================================
// Small
var small = UTKModal.Create(""Small"", UTKModal.ModalSize.Small);
small.Show();
// Medium (기본)
var medium = UTKModal.Create(""Medium"", UTKModal.ModalSize.Medium);
medium.Show();
// Large
var large = UTKModal.Create(""Large"", UTKModal.ModalSize.Large);
large.Show();
// FullScreen
var full = UTKModal.Create(""FullScreen"", UTKModal.ModalSize.FullScreen);
full.Show();
// ========================================
// 3. 옵션 설정
// ========================================
var modal = UTKModal.Create(""설정"");
// 닫기 버튼 숨기기
modal.ShowCloseButton = false;
// 배경 클릭 시 닫기 비활성화
modal.CloseOnBackdropClick = false;
// 푸터 숨기기
modal.SetFooterVisible(false);
// 옵션 설정 후 표시
modal.Show();
// ========================================
// 4. 푸터 버튼 추가
// ========================================
var modal = UTKModal.Create(""확인 모달"");
modal.Add(new Label(""정말 삭제하시겠습니까?""));
var confirmBtn = new UTKButton(""삭제"") { Variant = UTKButton.ButtonVariant.Danger };
confirmBtn.RegisterCallback<ClickEvent>(_ =>
{
Debug.Log(""삭제 실행"");
modal.Close();
});
var cancelBtn = new UTKButton(""취소"") { Variant = UTKButton.ButtonVariant.Normal };
cancelBtn.RegisterCallback<ClickEvent>(_ => modal.Close());
modal.AddToFooter(cancelBtn);
modal.AddToFooter(confirmBtn);
modal.Show();
// ========================================
// 5. 폼 모달
// ========================================
var modal = UTKModal.Create(""사용자 정보"");
var nameField = new UTKInputField(""이름"");
var emailField = new UTKInputField(""이메일"");
modal.Add(nameField);
modal.Add(emailField);
var submitBtn = new UTKButton(""제출"") { Variant = UTKButton.ButtonVariant.Primary };
submitBtn.RegisterCallback<ClickEvent>(_ =>
{
Debug.Log($""Name: {nameField.value}, Email: {emailField.value}"");
modal.Close();
});
modal.AddToFooter(submitBtn);
modal.Show();
// ========================================
// 6. 프로그래밍 방식 닫기
// ========================================
var modal = UTKModal.Create(""타이머 모달"");
modal.Add(new Label(""3초 후 자동으로 닫힙니다.""));
modal.ShowCloseButton = false;
modal.CloseOnBackdropClick = false;
modal.Show();
// 3초 후 닫기
modal.schedule.Execute(() => modal.Close()).StartingIn(3000);
// ========================================
// 7. Async/Await 방식 (닫힐 때까지 대기)
// ========================================
var modal = UTKModal.Create(""설정"");
modal.Add(new Label(""모달 내용""));
var closeBtn = new UTKButton(""닫기"") { Variant = UTKButton.ButtonVariant.Primary };
closeBtn.OnClicked += () => modal.Close();
modal.AddToFooter(closeBtn);
// 모달이 닫힐 때까지 대기
await modal.ShowAsync();
Debug.Log(""모달이 닫혔습니다."");
// Async 폼 예시
var formModal = UTKModal.Create(""사용자 정보"");
var nameField = new UTKInputField(""이름"");
formModal.Add(nameField);
var submitBtn = new UTKButton(""제출"") { Variant = UTKButton.ButtonVariant.Primary };
submitBtn.OnClicked += () => formModal.Close();
formModal.AddToFooter(submitBtn);
await formModal.ShowAsync();
Debug.Log($""입력된 이름: {nameField.value}"");
// ========================================
// 8. IUTKModalContent<T> 결과 반환
// ========================================
// IUTKModalContent<T>를 구현한 콘텐츠 클래스 정의
// public class UserFormContent : VisualElement, IUTKModalContent<UserData>
// {
// private UTKInputField _nameField = new(""이름"");
// private UTKInputField _emailField = new(""이메일"");
//
// public UserFormContent()
// {
// Add(_nameField);
// Add(_emailField);
// }
//
// public UserData? GetResult()
// {
// return new UserData(_nameField.value, _emailField.value);
// }
// }
// 사용
var modal = UTKModal.Create(""사용자 정보"");
var form = new UserFormContent();
modal.Add(form);
var submitBtn = new UTKButton(""제출"") { Variant = UTKButton.ButtonVariant.Primary };
submitBtn.OnClicked += () => modal.Close();
modal.AddToFooter(submitBtn);
// Close() 시 자동으로 form.GetResult() 호출
UserData? result = await modal.ShowAsync<UserData>();
if (result != null)
Debug.Log($""이름: {result.Name}, 이메일: {result.Email}"");",
uxmlCode: @"<!-- 네임스페이스 선언 -->
<ui:UXML xmlns:utk=""UVC.UIToolkit"">
<!-- 기본 모달 -->
<utk:UTKModal title=""설정"" size=""Medium"" show-close-button=""true"">
<ui:Label text=""모달 내용을 여기에 추가하세요"" />
</utk:UTKModal>
<!-- Small 모달, 닫기 버튼 없음 -->
<utk:UTKModal title=""알림"" size=""Small"" show-close-button=""false"">
<ui:Label text=""간단한 알림"" />
</utk:UTKModal>
<!-- 배경 클릭 닫기 비활성화 -->
<utk:UTKModal title=""중요"" size=""Medium"" close-on-backdrop-click=""false"">
<ui:Label text=""반드시 확인해야 하는 내용"" />
</utk:UTKModal>
</ui:UXML>");
}
private void ShowModalWithSize(UTKModal.ModalSize size)
{
if (_root == null) return;
var modal = UTKModal.Create($"{size} Modal", size);
modal.Add(new Label($"이것은 {size} 크기의 모달입니다."));
modal.OnClosed += () => Debug.Log($"{size} modal closed");
modal.Show();
}
#endregion
#region Notification Initializers
private void InitializeNotificationSample(VisualElement root)
{
if (_root == null) return;
UTKNotification.SetRoot(_root);
// Notification Types
var btnInfo = root.Q<UTKButton>("btn-noti-info");
btnInfo?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.ShowInfo("정보", "이것은 정보 알림입니다."));
var btnSuccess = root.Q<UTKButton>("btn-noti-success");
btnSuccess?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.ShowSuccess("성공", "작업이 성공적으로 완료되었습니다!"));
var btnWarning = root.Q<UTKButton>("btn-noti-warning");
btnWarning?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.ShowWarning("경고", "주의가 필요한 상황입니다."));
var btnError = root.Q<UTKButton>("btn-noti-error");
btnError?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.ShowError("오류", "오류가 발생했습니다!"));
// Position
var btnTopLeft = root.Q<UTKButton>("btn-noti-top-left");
btnTopLeft?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.Show("Top Left", "TopLeft 위치 알림",
UTKNotification.NotificationType.Info, UTKNotification.NotificationPosition.TopLeft));
var btnTopRight = root.Q<UTKButton>("btn-noti-top-right");
btnTopRight?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.Show("Top Right", "TopRight 위치 알림",
UTKNotification.NotificationType.Info, UTKNotification.NotificationPosition.TopRight));
var btnBottomLeft = root.Q<UTKButton>("btn-noti-bottom-left");
btnBottomLeft?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.Show("Bottom Left", "BottomLeft 위치 알림",
UTKNotification.NotificationType.Info, UTKNotification.NotificationPosition.BottomLeft));
var btnBottomRight = root.Q<UTKButton>("btn-noti-bottom-right");
btnBottomRight?.RegisterCallback<ClickEvent>(_ =>
UTKNotification.Show("Bottom Right", "BottomRight 위치 알림",
UTKNotification.NotificationType.Info, UTKNotification.NotificationPosition.BottomRight));
// With Actions
var btnAction = root.Q<UTKButton>("btn-noti-action");
btnAction?.RegisterCallback<ClickEvent>(_ =>
{
var notification = UTKNotification.Show("업데이트 가능",
"새로운 버전이 있습니다. 업데이트하시겠습니까?",
UTKNotification.NotificationType.Info, UTKNotification.NotificationPosition.TopRight);
notification.AddAction("업데이트", "update");
notification.AddAction("나중에", "later");
notification.OnActionClicked += (actionId) =>
{
Debug.Log($"Action clicked: {actionId}");
};
});
var btnPersistent = root.Q<UTKButton>("btn-noti-persistent");
btnPersistent?.RegisterCallback<ClickEvent>(_ =>
{
var notification = UTKNotification.Show("수동 닫기",
"이 알림은 자동으로 닫히지 않습니다. X 버튼을 눌러 닫아주세요.",
UTKNotification.NotificationType.Warning, UTKNotification.NotificationPosition.TopRight,
duration: 0);
notification.OnClosed += () => Debug.Log("Persistent notification closed");
});
SetCodeSamples(root,
csharpCode: @"// Root 설정 (한 번만)
UTKNotification.SetRoot(rootVisualElement);
// ========================================
// 1. 기본 알림 타입
// ========================================
// Info
UTKNotification.ShowInfo(""정보"", ""이것은 정보 알림입니다."");
// Success
UTKNotification.ShowSuccess(""성공"", ""작업이 완료되었습니다!"");
// Warning
UTKNotification.ShowWarning(""경고"", ""주의가 필요합니다."");
// Error
UTKNotification.ShowError(""오류"", ""오류가 발생했습니다!"");
// ========================================
// 2. 위치 지정
// ========================================
UTKNotification.Show(""제목"", ""메시지"",
UTKNotification.NotificationType.Info,
UTKNotification.NotificationPosition.TopRight); // 기본값
UTKNotification.Show(""제목"", ""메시지"",
UTKNotification.NotificationType.Success,
UTKNotification.NotificationPosition.BottomLeft);
// ========================================
// 3. 지속 시간 설정
// ========================================
// 기본 5초
UTKNotification.ShowInfo(""정보"", ""5초 후 자동 닫힘"");
// 10초
UTKNotification.ShowInfo(""정보"", ""10초 후 자동 닫힘"", duration: 10000);
// 수동 닫기 (자동 닫힘 없음)
UTKNotification.ShowWarning(""경고"", ""수동으로 닫아주세요."", duration: 0);
// ========================================
// 4. 액션 버튼 추가
// ========================================
var notification = UTKNotification.Show(
""업데이트 가능"", ""새로운 버전이 있습니다."",
UTKNotification.NotificationType.Info,
UTKNotification.NotificationPosition.TopRight);
notification.AddAction(""업데이트"", ""update"");
notification.AddAction(""나중에"", ""later"");
notification.OnActionClicked += (actionId) =>
{
if (actionId == ""update"")
Debug.Log(""업데이트 시작"");
else
Debug.Log(""나중에 업데이트"");
};
// ========================================
// 5. 닫힘 이벤트
// ========================================
var noti = UTKNotification.ShowInfo(""알림"", ""메시지"");
noti.OnClosed += () => Debug.Log(""알림이 닫혔습니다."");
// ========================================
// 6. 인스턴스 직접 생성
// ========================================
var custom = new UTKNotification(""제목"", ""메시지"", UTKNotification.NotificationType.Success);
custom.Duration = 0;
custom.AddAction(""확인"", ""confirm"");
rootVisualElement.Add(custom);");
}
#endregion
#region Picker Initializers
private void InitializeColorPickerSample(VisualElement root)
{
if (_root == null) return;
UTKColorPicker.SetRoot(_root);
_colorPreviewBox = root.Q<VisualElement>("color-preview-box");
_colorHexLabel = root.Q<Label>("color-hex-label");
if (_colorPreviewBox != null)
{
_colorPreviewBox.style.backgroundColor = _selectedColor;
}
var btnAlpha = root.Q<UTKButton>("btn-color-alpha");
btnAlpha?.RegisterCallback<ClickEvent>(_ => OpenColorPicker(true));
var btnNoAlpha = root.Q<UTKButton>("btn-color-no-alpha");
btnNoAlpha?.RegisterCallback<ClickEvent>(_ => OpenColorPicker(false));
var btnAsync = root.Q<UTKButton>("btn-color-async");
btnAsync?.RegisterCallback<ClickEvent>(_ => OpenColorPickerAsync().Forget());
SetCodeSamples(root,
csharpCode: @"// Root 설정 (한 번만)
UTKColorPicker.SetRoot(rootVisualElement);
// ========================================
// 1. Callback 방식
// ========================================
// Alpha 포함 (기본)
var picker = UTKColorPicker.Show(Color.white, ""색상 선택"", useAlpha: true);
// 색상 변경 이벤트 (실시간)
picker.OnColorChanged += (color) =>
{
Debug.Log($""색상 변경: {ColorUtility.ToHtmlStringRGBA(color)}"");
// 미리보기 업데이트 등
};
// 최종 선택 이벤트
picker.OnColorSelected += (color) =>
{
Debug.Log($""색상 선택됨: {ColorUtility.ToHtmlStringRGBA(color)}"");
// 최종 색상 적용
};
// 취소 이벤트
picker.OnCancelled += () =>
{
Debug.Log(""색상 선택이 취소되었습니다."");
};
// Alpha 없이 (RGB만)
var pickerNoAlpha = UTKColorPicker.Show(
Color.red,
""색상 선택 (Alpha 없음)"",
useAlpha: false
);
// ========================================
// 2. Async/Await 방식 (권장)
// ========================================
// Alpha 포함
Color result = await UTKColorPicker.ShowAsync(
Color.white,
""색상 선택 (Async)"",
useAlpha: true
);
Debug.Log($""선택된 색상: #{ColorUtility.ToHtmlStringRGBA(result)}"");
// Alpha 없이
Color rgbColor = await UTKColorPicker.ShowAsync(
Color.red,
""RGB 색상 선택"",
useAlpha: false
);
Debug.Log($""선택된 RGB: #{ColorUtility.ToHtmlStringRGB(rgbColor)}"");
// 사용 예시
public async UniTask ChangeBackgroundColorAsync()
{
Color newColor = await UTKColorPicker.ShowAsync(
_currentBackgroundColor,
""배경 색상 선택"",
useAlpha: true
);
_currentBackgroundColor = newColor;
ApplyBackgroundColor(newColor);
}");
}
private void OpenColorPicker(bool useAlpha)
{
if (_root == null) return;
var picker = UTKColorPicker.Show(_selectedColor, "Select Color", useAlpha);
picker.OnColorChanged += (color) =>
{
if (_colorPreviewBox != null)
_colorPreviewBox.style.backgroundColor = color;
if (_colorHexLabel != null)
_colorHexLabel.text = useAlpha
? $"#{ColorUtility.ToHtmlStringRGBA(color)}"
: $"#{ColorUtility.ToHtmlStringRGB(color)}";
};
picker.OnColorSelected += (color) =>
{
_selectedColor = color;
Debug.Log($"Color Selected: #{(useAlpha ? ColorUtility.ToHtmlStringRGBA(color) : ColorUtility.ToHtmlStringRGB(color))}");
};
}
private async UniTaskVoid OpenColorPickerAsync()
{
if (_root == null) return;
Color result = await UTKColorPicker.ShowAsync(_selectedColor, "Select Color (Async)", useAlpha: true);
_selectedColor = result;
if (_colorPreviewBox != null)
_colorPreviewBox.style.backgroundColor = result;
if (_colorHexLabel != null)
_colorHexLabel.text = $"#{ColorUtility.ToHtmlStringRGBA(result)}";
Debug.Log($"[Async] Color Result: #{ColorUtility.ToHtmlStringRGBA(result)}");
}
private void InitializeDatePickerSample(VisualElement root)
{
if (_root == null) return;
UTKDatePicker.SetRoot(_root);
UTKDatePicker.SetDayNames(new[] { "일", "월", "화", "수", "목", "금", "토" });
_dateLabel = root.Q<Label>("date-label");
_rangeDateLabel = root.Q<Label>("range-date-label");
if (_dateLabel != null)
_dateLabel.text = $"Selected: {_selectedDate:yyyy-MM-dd}";
if (_rangeDateLabel != null)
_rangeDateLabel.text = $"Range: {_rangeStartDate:yyyy-MM-dd} ~ {_rangeEndDate:yyyy-MM-dd}";
var btnDateOnly = root.Q<UTKButton>("btn-date-only");
btnDateOnly?.RegisterCallback<ClickEvent>(_ => OpenDatePicker(UTKDatePicker.PickerMode.DateOnly));
var btnDateTime = root.Q<UTKButton>("btn-date-time");
btnDateTime?.RegisterCallback<ClickEvent>(_ => OpenDatePicker(UTKDatePicker.PickerMode.DateAndTime));
var btnDateAsync = root.Q<UTKButton>("btn-date-async");
btnDateAsync?.RegisterCallback<ClickEvent>(_ => OpenDatePickerAsync().Forget());
var btnRange = root.Q<UTKButton>("btn-range");
btnRange?.RegisterCallback<ClickEvent>(_ => OpenDateRangePicker());
var btnRangeAsync = root.Q<UTKButton>("btn-range-async");
btnRangeAsync?.RegisterCallback<ClickEvent>(_ => OpenDateRangePickerAsync().Forget());
SetCodeSamples(root,
csharpCode: @"// Root 설정 (한 번만)
UTKDatePicker.SetRoot(rootVisualElement);
// 요일 이름 설정 (선택사항, 한 번만)
UTKDatePicker.SetDayNames(new[] { ""일"", ""월"", ""화"", ""수"", ""목"", ""금"", ""토"" });
// ========================================
// 1. 단일 날짜 선택 - Callback 방식
// ========================================
// Date Only
var datePicker = UTKDatePicker.Show(
DateTime.Today,
UTKDatePicker.PickerMode.DateOnly,
""날짜 선택""
);
datePicker.OnDateSelected += (date) =>
{
Debug.Log($""선택된 날짜: {date:yyyy-MM-dd}"");
};
datePicker.OnCancelled += () =>
{
Debug.Log(""날짜 선택이 취소되었습니다."");
};
// Date & Time
var dateTimePicker = UTKDatePicker.Show(
DateTime.Now,
UTKDatePicker.PickerMode.DateAndTime,
""날짜 및 시간 선택""
);
dateTimePicker.OnDateSelected += (date) =>
{
Debug.Log($""선택된 날짜/시간: {date:yyyy-MM-dd HH:mm}"");
};
// ========================================
// 2. 단일 날짜 선택 - Async/Await 방식 (권장)
// ========================================
// Date Only
DateTime? dateResult = await UTKDatePicker.ShowAsync(
DateTime.Today,
UTKDatePicker.PickerMode.DateOnly,
""날짜 선택 (Async)""
);
if (dateResult.HasValue)
{
Debug.Log($""선택된 날짜: {dateResult.Value:yyyy-MM-dd}"");
}
else
{
Debug.Log(""날짜 선택이 취소되었습니다."");
}
// Date & Time
DateTime? dateTimeResult = await UTKDatePicker.ShowAsync(
DateTime.Now,
UTKDatePicker.PickerMode.DateAndTime,
""날짜 및 시간 선택""
);
if (dateTimeResult.HasValue)
{
Debug.Log($""선택된 날짜/시간: {dateTimeResult.Value:yyyy-MM-dd HH:mm}"");
}
// ========================================
// 3. 날짜 범위 선택 - Callback 방식
// ========================================
var rangePicker = UTKDatePicker.ShowRange(
DateTime.Today,
DateTime.Today.AddDays(7),
includeTime: false,
""기간 선택""
);
rangePicker.OnDateRangeSelected += (start, end) =>
{
Debug.Log($""선택된 기간: {start:yyyy-MM-dd} ~ {end:yyyy-MM-dd}"");
};
rangePicker.OnCancelled += () =>
{
Debug.Log(""기간 선택이 취소되었습니다."");
};
// ========================================
// 4. 날짜 범위 선택 - Async/Await 방식 (권장)
// ========================================
var rangeResult = await UTKDatePicker.ShowRangeAsync(
DateTime.Today,
DateTime.Today.AddDays(7),
includeTime: false,
""기간 선택 (Async)""
);
if (rangeResult.HasValue)
{
Debug.Log($""선택된 기간: {rangeResult.Value.Start:yyyy-MM-dd} ~ {rangeResult.Value.End:yyyy-MM-dd}"");
}
else
{
Debug.Log(""기간 선택이 취소되었습니다."");
}
// 시간 포함 범위 선택
var rangeTimeResult = await UTKDatePicker.ShowRangeAsync(
DateTime.Now,
DateTime.Now.AddDays(7),
includeTime: true,
""기간 및 시간 선택""
);
if (rangeTimeResult.HasValue)
{
Debug.Log($""시작: {rangeTimeResult.Value.Start:yyyy-MM-dd HH:mm}"");
Debug.Log($""종료: {rangeTimeResult.Value.End:yyyy-MM-dd HH:mm}"");
}");
}
private void OpenDatePicker(UTKDatePicker.PickerMode mode)
{
if (_root == null) return;
string title = mode == UTKDatePicker.PickerMode.DateOnly ? "Select Date" : "Select Date & Time";
var picker = UTKDatePicker.Show(_selectedDate, mode, title);
picker.OnDateSelected += (date) =>
{
_selectedDate = date;
if (_dateLabel != null)
{
_dateLabel.text = mode == UTKDatePicker.PickerMode.DateOnly
? $"Selected: {date:yyyy-MM-dd}"
: $"Selected: {date:yyyy-MM-dd HH:mm}";
}
Debug.Log($"Date Selected: {date:yyyy-MM-dd HH:mm}");
};
}
private async UniTaskVoid OpenDatePickerAsync()
{
if (_root == null) return;
DateTime? result = await UTKDatePicker.ShowAsync(_selectedDate, UTKDatePicker.PickerMode.DateOnly, "Select Date (Async)");
if (result.HasValue)
{
_selectedDate = result.Value;
if (_dateLabel != null)
_dateLabel.text = $"Selected: {result.Value:yyyy-MM-dd}";
Debug.Log($"[Async] Date Result: {result.Value:yyyy-MM-dd}");
}
else
{
Debug.Log("[Async] Date selection cancelled");
}
}
private void OpenDateRangePicker()
{
if (_root == null) return;
var picker = UTKDatePicker.ShowRange(_rangeStartDate, _rangeEndDate, false, "Select Date Range");
picker.OnDateRangeSelected += (start, end) =>
{
_rangeStartDate = start;
_rangeEndDate = end;
if (_rangeDateLabel != null)
_rangeDateLabel.text = $"Range: {start:yyyy-MM-dd} ~ {end:yyyy-MM-dd}";
Debug.Log($"Date Range Selected: {start:yyyy-MM-dd} ~ {end:yyyy-MM-dd}");
};
}
private async UniTaskVoid OpenDateRangePickerAsync()
{
if (_root == null) return;
var result = await UTKDatePicker.ShowRangeAsync(_rangeStartDate, _rangeEndDate, false, "Select Date Range (Async)");
if (result.HasValue)
{
_rangeStartDate = result.Value.Start;
_rangeEndDate = result.Value.End;
if (_rangeDateLabel != null)
_rangeDateLabel.text = $"Range: {result.Value.Start:yyyy-MM-dd} ~ {result.Value.End:yyyy-MM-dd}";
Debug.Log($"[Async] Range Result: {result.Value.Start:yyyy-MM-dd} ~ {result.Value.End:yyyy-MM-dd}");
}
else
{
Debug.Log("[Async] Date range selection cancelled");
}
}
#endregion
}