八、研究UI元件:Segmented Control
這系列一共要研究以下九個元件。會分別研究兩種寫法:storyboard以及純code。以及其他我覺得要額外研究的小東西(也可能沒有)
- Segmented Control
- Slider
- Switch
- Activity Indicator View
- Progress View
- Page Control
- Date Picker
- Visual Effect View with Blur
- Color Well
每次在大潤發樓上的路易莎學寫扣都會一直流鼻水。
Segmented Control
控制元件家族之一。可讓user切換欄位、切換分頁等。
蘋果文件說明:A horizontal control that consists of multiple segments, each segment functioning as a discrete button.
元件庫說明:The segments can represent single or multiple selection, or a list of commands. Each segment can display text or an image, but not both.
研究欄位
- Segments:設定有幾個欄位。(需為2以上)
- Segment:點開後可選擇各欄位切換做詳細設定。
- Title:欄位顯示的字
- Image:欄位也可顯示圖片(但Title與Image只能擇一)
- Selected:預設畫面出現時選中的欄位。
Segmented Control storyboard
Create UISegmentedControl Programmatically
邊參考蘋果文件,邊隨手試試看,先寫出各欄位的title與元件的大小、位置之後,UISegmentedControl會長這樣。從「Managing segment behavior and appearance」跟「Customizing appearance」應就可以弄的跟storyvboard元件庫的一樣。
import UIKit
class ViewController: UIViewController {
let SC = UISegmentedControl()
override func viewDidLoad() {
super.viewDidLoad()
//插入各欄位與設定其所在位置,並設定文字。
SC.insertSegment(withTitle: "one", at: 0, animated: false)
SC.insertSegment(withTitle: "two", at: 1, animated: false)
SC.insertSegment(withTitle: "three", at: 2, animated: false)
//Segmented Control大小與位置
SC.frame = CGRect(x: 0 , y: view.center.y, width: 300, height: 50)
//設定各欄位寬度(不特別設定的話應為平均分配)
//SC.setWidth(100.0, forSegmentAt: 0)
view.addSubview(SC)
}
}
使用storyboard Size Inspector時,高度為系統設定,不可隨意更動。純code則可隨意控制。
另外,純code只有一個欄位時不會報錯;使用storyboard Size Inspector時則需兩個以上。當然通常也不會只做一個啦lol
參考文章: