SwiftUI:视图组件

前言

 


  

  SwiftUI有很多不同的视图控件,包含了Controls容器  控件容器

                    Layout容器    布局容器

                    Paints容器     绘画容器

                    Other容器      其他容器

 

一.Controls容器

 


 

  Button        Color Picker    Data Picker      Disclosure Group

  (按钮)       (颜色取色器)    (数据选取器)      (折叠组)

  Edit Button      Form       Group Box          Label

  (编辑按钮)       (表格)       (组框)           (标签)

  Link          List         Navigation Link    Navigation View

      (链接)         (列表)       (导航链接)      (导航视图)

  Outline Group      Picker        Progress View      Scroll View

  (大纲组)        (选取器)         (进度)        (滚动)

  Section        Secure Field    SignInWithAppleButton   Slider

     (片段)        (密码框)         (苹果登陆)        (滑动)

  Stepper       Tab View      Text           Text Editor

   (叠加)         (页面)      (文本)         (文本编辑)

  Text Field      Toggle

  (文本框)      (切换)

 

都是组 :Group Box + Dislosure Group + Outline Group

都是框: Text Field + Secure Field

都是view : Navigation View + Tab view 

 


  

   进行分类

 

1.Button

 


 

  Button 按钮控件

  用户需要提供 操作 和 标签 来创建按钮

  操作是一个方法或闭包属性,当用户单击或轻触按钮时,它会执行

  标签是描述按钮的视图

 

Button(action : Action){

  Content

}

 


 

Button.init("按钮名"){. //Button("按钮名")

  print("输出")

}

 

复制代码
Button(action : {

  print("输出")

}){

  Text("Button")

} 
复制代码

 

2.Color Picker

 


 

  Color Picker  颜色取色器  用于打开ios的颜色选取

 

ColorPicker("Title", selection : .constant(.red))

 


 

@State private var bgColor = Color(.sRGB, red : 0.98, green : 0.9, blue : 0.2)


ColorPicker("颜色取色器", selection : $bgColor)

 

3.Data Picker

 


 

  Data Picker  数据选取器  用于选取日期时间等数据

 

DataPicker(selection : .constant(Date()), label : {Text("Date")})

 


 

@State private var date = Date()

DatePicker("数据选取器", selection : $date,  displayedComponents : [.date])

 

4.Dislosuure Group

 


 

  Disclosure Group  公开组控件  用于展开显示或者折叠隐藏组内容

 

DisclosureGroup("Group")
{
  Content  
}

 


 

复制代码
struct ToggleStates
{
  var oneIsOn : Bool = false
  var twoIsOn : Bool = true    
}

@State private var toggleStates = ToggleStates()
@State private var topExpanded : Bool = true

DisclosureGroup("Items", isExpanded : $topExpanded)
{
  Toggle("Toggle 1", isOn : $toggleStates.oneIsOn)
  Toggle("Toggle 2", isOn : $toggleStates.twoIsOn)

  DisclosureGroup("Sub-items")
  {
    Text("Sub-item 1")    
  }     
}    
复制代码

 

5.Edit Button

 


 

  Edit Button 编辑按钮控件  用于按钮显示Edit和Done两种状态

 

EditButton()

 


  

//例如 NavigationView可以用EditButton来编辑列表

 

6.Form + 10.List

 


 

  Form    表格控件   用于绘制表格

  List  列表控件   用于排列其他控件

 

  这两个控件有点类似,都可以排列一些控件

  在视图上List的数据和背景都是白色。Form的数据是白色,背景是灰色。而Form不能添加selection组件

  这两个控件都可以包含section对自己排列的东西进行表头和表尾的添加,还可以添加间隔的作用

 

Form 
{
  Content  
}

 

List
{
  Content  
}

  

7.Group Box

 


 

  Group Box 组框控件   用于组合一些控件在一起,常用于统计 历史记录 信息数据  成就等  

 

GroupBox(label : Label)
{
  Content  
}

 


 

复制代码
@State var text : String = ""

var body : some View
{
  GroupBox(label : Label("Label", systemImage : "clock"))
  {
      VStack
      {
            TextField("Username", text : $text)
            Button(action : {})
            {
                Text("Submit")
            }  
      }
  }
}    
复制代码

 

8.Label

 


 

  标签控件,包含文字和图片

 

Label("label", systemImage : "42.circle" )

 

9.Link

 


  

  Link 链接控件  用于打开网页URL

 

Link(destination : URL)
{
  Text("Link")  
}

 


 

Linkl("link", destination : URL(string : "https://www.example.com/TOS.html")!)

 

11.Navigation Link + 12.Navigation View

 


 

  Navigation Link 导航链接  用于跳转到另一个SwiftUI视图,必须添加Navigation View才能够跳转

  Navigation View 导航视图   用于最大视图的包围组件,因为它包括了上面回跳标题,

                                              最上面的就是用这个组件     最下面的就是Tab View组件

 

复制代码
NavigationLink(destination : Destination)

{

  Label Content

}



NavigationView

{

  NavigationLink(destination : Destination)

  {

    Content

  }

}
复制代码

 


 

复制代码
NavigationView 

{

  List

  {

    NavigationLink(destination : ViewOne())  // ViewOne 是一个SwiftUI视图文件

    {

      Text("VIewOne")

    }

    NavigationLink(destination : ViewTwo())

    {

      Text("VIewTwo")

    }

  }

  .navigationBarTitle(Text("视图切换"), displayMode : .large)

} 
复制代码

 

复制代码
@State private var ViewOneBool : Bool = false

 

NavigationView 

{

  List

  {

    NavigationLink(destination : ViewOne())  // ViewOne 是一个SwiftUI视图文件

    {

      Text("VIewOne")

    }

    NavigationLink(destination : ViewTwo())

    {

      Text("VIewTwo")

    }

    //添加一个按钮来控制跳转

    Button("自动调整")

    {

      self.ViewOneBool = true

    }

  }

  .navigationBarTitle(Text("视图切换"), displayMode : .large)

} 
复制代码

 

13.Outline Group

 


 

  Outline Group  大纲组  用于添加多个折叠组

                用户通过使用公开视图来展开和折叠分支来导航树结构,类似文件系统结构

 

OutlineGroup(data : _, id : KeyPath<DataElement, _>, children : KeyPath<DataElement, _?>)
{
  element in Text("Placeholder")  
}

 


 

复制代码
struct FileItem: Hashable, Identifiable, CustomStringConvertible {
    var id: Self { self }
    var name: String
    var children: [FileItem]? = nil
    var description: String {
        switch children {
        case nil:
            return "📄 \(name)"
        case .some(let children):
            return children.isEmpty ? "📂 \(name)" : "📁 \(name)"
        }
    }
}


let data =
  FileItem(name: "users", children:
    [FileItem(name: "user1234", children:
      [FileItem(name: "Photos", children:
        [FileItem(name: "photo001.jpg"),
         FileItem(name: "photo002.jpg")]),
       FileItem(name: "Movies", children:
         [FileItem(name: "movie001.mp4")]),
          FileItem(name: "Documents", children: [])
      ]),
     FileItem(name: "newuser", children:
       [FileItem(name: "Documents", children: [])
       ])
    ])



        OutlineGroup(data, children: \.children) { item in
            Text("\(item.description)")
        }
复制代码

 

14.Picker

 


 

  Picker  选取器  用于选取一些数据

 

Picker(selection : .constant(1), label : Text("Picker"))
{
  Text("1").tag(1)
  Text("2").tag(2)    
}

 

15.Progress View

 


 

  Progress View  进度视图控件 用于显示进度条

 

ProgressView(value : 0.5)

 


 

@State private var progress = 0.5

ProgressView( value : progress )

 

16.Scroll View

 


 

  Scroll View  滚动条视图控件 

 

ScrollView
{
  Content  
}

 


 

 

复制代码
ScrollView(.vertical, showsIndicators : true)
{
  VStack(spacing : 10)
  {
    ForEach(0 ..< 100)
     {
        Text("Item \($0)")
           .font(.title)      
    }             
  }      
}    
复制代码

 

17.Section

 


 

  Section 片段控件  用于添加一段章节的标题和页脚等  

            一般包含在List或Form组件内,进行内容的排列中表头和表尾的添加,也可以起到间隔的作用

             用于 分层视图

 

Section
{
  Content  
}

 


 

复制代码
// 配合List Picker Form

List
{
    Section(header : Text("k1"), footer : Text("k2"))
    {
        Text("k3")
    }
            
    Section(header : Text("k4"), footer : Text("k5"))
    {
        Text("k6")
    }
}            
复制代码

 

18.Secure Field

 


 

  Secure Field  密码框  用于输入账号密码

 

SecureField(Label, text : Value)

 


 

@State private var password : String = ""

SecureField("密码框", text : $password)

 

19.SignInWithAppleButton

 


 

  SignInWithAppleButton  苹果登陆控件  用于支持苹果ID注册登陆

 

20.Slider

 


 

  Slider 滑动控件  用于滑动值

 

Slider(value : Value)

 


 

// 必须是浮点数
@State private var sliderDouble : Double = 50.0

Slider(value : $sliderDouble)

 

复制代码
@State private var sliderDouble : Double = 50.0
@State private var sliderBool : Bool = false

Slider(value : $sliderDouble, in : 0 ... 100, step : 2
         onEditingChanged{editing in sliderBool = sliderBool},

          minimumValueLabel: Text("0"),

          maximumValueLabel: Text("100")

      )

复制代码

 

21.Stepper

 


 

  Stepper 叠加控件  用于增加或减少数量

 

Stepper(value : Value, in : Range)
{
    Label
}

 


 

@State private var value = 0
let range = 1...50
let step = 5

Stepper(value : $value, in : range,  step : step)
{
    Text("\(value),\(range.description),\(step)")
}

 

复制代码
@State private var value = 0 
let colors : [Color] = [.orange, 
                                .red, 
                                .gray, 
                                .blue,
                                .green, 
                                .purple,
                                .pink]

func incrementStep()
{
   value += 1
    if value >= colors.count { value = 0 }
}
                           
func decrementStep()
{
  value -= 1
  if value < 0 { value = colors.count - 1 }
}

Stepper
{
  onIncrement : incrementStep,
  onDecrement : decrementStep
  {
    Text("\(value),\(colors[value].description)")
  }
}
复制代码

 

22.Tab View

 


 

  Tab View 页面控件  用于底下切换不同的页面

 

复制代码
TabView
{

  Text("The First Tab")
    .tabItem
    {
      Image(systemName : "1.square.fill")
      Text("First")  
    }       

  Text("The Second Tab")
    .tabItem
    {
      Image(systemName : "2.square.fill")
      Text("Second")  
    } 
 
}
复制代码

 

23.Text

 


 

  Text 文本控件

 

Text("文本")

 

24.Text Editor

 


 

  Text Editor 文本编辑控件

 

TextEditor(text: .constant("Placeholder"))

 


 

@State private var textEditorString : String = "文本"

TextEditor(text : $textEditorString)

 

25.Text Field

 


 

  Text Field 文本框控件  用于获取用户输入信息

 

TextField("默认文本", text : Value)    //一般用变量代替Value

 


 

@State private var textFieldString : String = “默认文本”

TextField("默认文本", text : $textFieldString)

 

//增加回调函数
//当用户开始编辑文本会调用 onEditingChanged
//当用户回车等会调用 onCommit

 

26.Toggle

 


 

  Toggle 切换控件  用于切换状态

 

Toggle(isOn : Is On)
{
   Label()       
}

 


 

@State private var toggleBool : Bool = false

Toggle(isOne : $toggleBool)
{
  Text("切换")  
}

Toggle("切换", isOn : toggleBool)

 

二.Layout容器

 


 

  布局容器用来容纳各种组件的排布顺序

  Depth Stack      Geometry Reader    Horizontal Stack     Lazy Horizontal Grid    

  (深度栈)        (对象读取)        (水平栈)                     (延迟水平网格)

  Lazy Horizontal Stack   Lazy Vertical Grid     Lazy Vertial Stack    Scroll View Reader

     (延迟水平栈)                  (延迟垂直网格)                  (延迟垂直栈)      (滚动视图读取)

  Spacer         Vertical Stack  

  (间隔器)         (垂直栈)

 

延迟:当视图布局中,数据量大的时候采用延迟布局

 

1.Depth Stack + 3.Horizontal Stack + 10.Vertical Stack

 


 

  Depth Stack 深度器

  Horizontal Stack 水平器

  Vertical Stack 垂直器

 

复制代码
ZStack
{

  Content

}

 

HStack
{

  Content

}

 

VStack
{

  Content

}
复制代码

 


 

HStack
(
  alignment : .top,     //靠上对齐 
  spacing : 10           //间隔10  
)
{

}

 

2.Geometry Reader

 


 

  Geometry Reader  对象读取  用于子view获取到父view对象的信息读取

 

复制代码
struct MyRectangle : View
{
  var body : some View
  {
      Rectangle().fill(Color.green)  
  }  
}

struct GeometryReaderView : View
{
  var body : some View
  {
      HStack(spacing : 0)
      {
         Text("举个例子")
         MyRectangle()
      }
      .frame(width : 200, height : 100, alignment : .center)
      .border(Color.green, width : 1)
  }
}    
复制代码

 

复制代码
struct MyRectangle : View
{
    var body : some View
    {
        Rectangle().fill(Color.green)
    }
}

//对象读取布局
struct GeometryReaderView: View {
    var body: some View {
        
        GeometryReader
        {
            proxy in
            HStack(spacing : 0)
            {
                Text("举个例子, \(proxy.size.width)")
                MyRectangle()
            }
            .border(Color.green, width : 1)
        }
        .frame(width : 200, height : 100, alignment : .center)
    }
}
复制代码

 

4.Lazy Horizontal Grid + 6.Lazy Vertical Grid

 


 

  Lazy Horizontal Grid  延迟水平网格

  Lazy Vertical Grid      延迟垂直网格

 

复制代码
LazyHGrid(rows : Rows)
{
  Text("Placeholder")
  Text("Placeholder")    
}

LazyVGrid(columns : Columns)
{
  Text("Placeholder")
  Text("Placeholder")    
}
复制代码

 

5.Lazy Horizontal Stack + 7.Lazy Vertical Stack

 


  

  Lazy Horizontal Stack  延迟水平栈  仅在需要时创建,延迟加载,性能考虑

  Lazy Vertical Stack    延迟垂直栈      仅在需要时创建,延迟加载,性能考虑

 

LazyVStack
{
  ForEach(1 ... 10, id : \.self)
  {
    count in Content        
  }
}

 

8.Scroll View Reader

 


 

  Scroll View Reader  滚动视图读取  用于获取滚动视图读取位置信息等

 

9.Spacer

 


 

  间隔器

  

Spacer()

    

三.Paints容器

1.Angular Gradient

 

2.Linear Gradient

 

3.Radial Gradient

 

 

四.Other容器

 


  

  Capsule         Circle     Color     Container Relative Shape

   (椭圆)          (圆)     (颜色)              (容器相对形状)

  Drivider         Ellipse    Empty View    Group

   (分割)         (椭圆形)    (空白)       (组)

  Image         Menu     Path      Rectangle

  (图片)         (菜单)     (路径)     (矩形)

  Rounded Rectangle

     (圆角矩形)

 

内置形状 :Rectangle 矩形 + Rounded Rectangle 圆角矩形 +  Capsule 胶囊 + Ellipse 椭圆形 + Circle 圆形

      

1.Capsule

 


  

  Capsule  椭圆  用于显示椭圆

 

Capsule()

 

2.Circle

 


 

  Circle  圆形  用于显示圆形

 

Circle()

 

3.Color

 


 

  Color  颜色控件  用于显示颜色

 

Color(red : 0.5, green : 0.5, blue : 0.5)

 

4.Container Relative Shape

 


 

  Container Relative Shape 容器相对形状 用于被当前容器形状的插入版本替换的形状。如果没有定义容器形状,则用矩形替换。 

 

 

5.Drivider

 


 

  Drivider  分割线   用于分割屏幕

 

Divider()

 

6.Ellipse

 


  

  Ellipse  椭圆形  用于显示椭圆形

 

Ellipse()

 

7.Empty View

 


 

  Empty View 空白视图  用于填充空白视图

 

EmptyView()

 

8.Group

 


 

  Group  组  用于整合一些控件 

           由于一个View最多只能有十个子View,所以一个视图中如果子视图过多,就要进行分组显示

 

Group
{
  Content  
}

 

9.Image

 


 

   Image  图像  用于显示图像

 

Image("Image Name")

 

10.Menu

 


 

  Menu  菜单   用于打开多个菜单栏

 

Menu("Menu")
{
  Text("Menu Item 1")
  Text("Menu Item 2")
  Text("Menu Item 3")      
}

 

复制代码
Menu
{
  Text("Menu Item 1")
  Text("Menu Item 2")
  Text("Menu Item 3")      
}label :
{
  Label("PDF", systemImage : "doc.fill")  
}
复制代码

 

11.Path

 


 

  Path  路径绘制和 封装成 shape 形状绘制 

 

Path(ellipseIn : CGRect(x : 0, y : 0, width : 50, height : 100))

 


 

 

 

12.Rectangle

 


 

  Rectangle  矩形  用于显示矩形

 

Rectangle()
        
Rectangle()
            .fill(Color.orange)
            .frame(width: 200, height: 200)
            .scaleEffect(0.6)

 

13.Rounded Rectangle

 


 

  Rounded Rectangle  圆角矩形  用于显示圆角矩形

 

RoundedRectangle(cornerRadius : Corner Radius)

RoundedRectangle(cornerRadius: 120)

 

posted @   言午丶  阅读(654)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示