“`markdown
## CocoaPods 安裝

要在 Swift 專案中使用 Material Components,首先需要透過 CocoaPods 進行安裝。請在你的 Podfile 中添加以下行:

“`sh
pod ‘MaterialComponents’
“`

接著,執行以下命令安裝所需的元件:

“`sh
pod install
“`

## 使用 Swift 創建按鈕與文本框

在導入 Material Components 後,你可以開始使用這些元件來增強你的應用程式界面。以下是如何創建一個提升的按鈕(Raised Button)和浮動文本框(Floating TextField)的範例。

### 創建提升的按鈕

首先,導入 MaterialButtons 模組:

“`swift
import MaterialComponents.MaterialButtons
“`

接著,在你的視圖控制器中,重寫 `viewWillAppear` 方法來創建並顯示按鈕:

“`swift
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

let raiseButton = MDCRaisedButton()
raiseButton.frame = CGRect(x: 100, y: 100, width: 100, height: 50) // 調整高度以符合設計要求
raiseButton.setTitle(“Raised Button”, for: .normal)
raiseButton.sizeToFit()
raiseButton.addTarget(self, action: #selector(tapped), for: .touchUpInside)
self.view.addSubview(raiseButton)
}

@objc func tapped() {
print(“Button tapped!”)
}
“`

### 創建浮動文本框

同樣,你可以創建一個浮動文本框,讓用戶輸入資料:

“`swift
import MaterialComponents.MaterialTextFields

let textFieldFloating = MDCTextField()
textFieldFloating.frame = CGRect(x: 100, y: 200, width: 200, height: 50) // 調整寬度與高度以符合設計要求
textFieldFloating.placeholder = “Enter text”
self.view.addSubview(textFieldFloating)
“`

## 錯誤排除

如果在使用 Material Components 時遇到問題,請檢查以下幾點:

– 確保你的 Podfile 正確且已成功執行 `pod install`。
– 檢查 Import 語句是否正確,並確保你已導入所有需要的模組。
– 確保在視圖控制器的生命週期方法中正確設置元件。

## 延伸應用

Material Design 是一種現代的設計風格,你可以利用這些元件創建其他 UI 元素,如切換開關、下拉選單等。這不僅能提升應用的美觀度,還能改善用戶體驗。

![Material Design Button Example](https://badgameshow.com/steven/wp-content/uploads/2020/11/cup-1-1.png “這是一個提升的 Material Design 按鈕範例”)

## Q&A(常見問題解答)

**Q1: 如何在 Swift 中使用 Material Components?**
A: 你需要在 Podfile 中安裝 MaterialComponents,然後在 Swift 檔案中導入相關模組即可開始使用。

**Q2: 如果按鈕沒有顯示,該怎麼辦?**
A: 確保你在正確的生命週期方法中添加按鈕,並檢查按鈕的 frame 是否位於可見區域內。

**Q3: Material Design 可以與 SwiftUI 一起使用嗎?**
A: 雖然 Material Design 主要針對 UIKit,但也有一些元件支持 SwiftUI。你可以查閱相關文檔以獲得更多資訊。
“`

Categorized in: