Text
- 可以对比参照UIKit中的UILabel
下面通过代码来举例,一些常用的属性和方法,更多内容可以参考后边的详细说明或者参阅官方文档
Text("Hello World")
//.frame(width: 160, height: 20, alignment: .leading)
.frame(minWidth: 50, idealWidth: 150, maxWidth: 300,
minHeight: 15, idealHeight: 30, maxHeight: 50,
alignment: .leading)//设置宽高以及对齐方式
//.fixedSize() //默认纵横向都固定为理想尺寸
.fixedSize(horizontal: true, vertical: false)//横向固定为理想尺寸
//.position(CGPoint(x: 20, y: 30)) //设置中心点坐标
.offset(x: 30, y: 30) //x,y偏移量
.padding(30) //设置上下左右边距为30
//.padding(.all, 10)
.font(Font.system(size: 15)) //字体大小
.foregroundColor(.purple) //字体颜色
.background(Color.yellow) //背景颜色
//在视图上覆盖一个视图,并设置其对齐方式
.overlay(Color.gray.opacity(0.5), alignment: .bottom)
.tag(1) //设置tag值
//Shape: 圆Circle, 圆角Capsule
.clipShape(Capsule(), style: FillStyle()) //裁剪形状
.cornerRadius(10) //圆角
.cornerRadius(10, antialiased: true) //圆角,裁剪的时候是否平滑
.border(Color.green, width: 1)//边框颜色及宽度
///移除了UIKit中的alpha
.opacity(0.8) //透明度
.shadow(radius: 0.5)
.shadow(color: .black, radius: 0.5, x: 2, y: 2)//阴影
.blur(radius: 0.8, opaque:false) //模糊效果
///手势
.onTapGesture { //tap手势事件
print("onTapGesture")
}
.onLongPressGesture {//长按手势事件
print("onLongPressGesture")
}
///事件,出现,消失,拷贝,剪切等等...
// 出现
.onAppear {
print("onAppear")
}
// 消失
.onDisappear {
print("onDisappear")
}
//事件控制
//.hidden() //隐藏
//.disabled(true) //是否禁止响应事件,默认为false
//.deleteDisabled(false) //是否禁止删除
//.moveDisabled(true) //是否禁止移动
// .overlay(, alignment: <#T##Alignment#>)
///单行时无效,多行才起作用
.multilineTextAlignment(.center) //多行文本时左对齐
.lineLimit(3) //限制行数,默认不限制,能否正确显示也受其frame大小和lineSpace的影响
.lineSpacing(5) //行间距
Creating a Text View(初始化)
init<S>(S)
Creates a text view that displays the specified content.
init(LocalizedStringKey, tableName: String?, bundle: Bundle?, comment: String?)
//国际化文字
Creates a text view that displays localized content identified by a key.
init(verbatim: String)
Creates a text view that displays the specified string.
typealias Text.Body
//Text.Body类型
Styling a Text View(格式:字体加粗,倾斜等等...)
func bold() -> Text
//加粗
Applies a bold font weight to the text.
func italic() -> Text
//倾斜
Applies italics to the text.
func fontWeight(Font.Weight?) -> Text
//字体粗细
Sets the font weight of the text.
func baselineOffset(CGFloat) -> Text
//基线
Sets the baseline offset for the text.
func tracking(CGFloat) -> Text
//通道
Sets the tracking for the text.
func kerning(CGFloat) -> Text
//字距
Sets the spacing, or kerning, between two characters.
func underline(Bool, color: Color?) -> Text
//下划线
Applies an underline to the text.
func strikethrough(Bool, color: Color?) -> Text
//删除线
Applies a strikethrough to the text.
Operating on Text Views(运算规则,可以做比较,也可以直接用+拼接)
static func == (Text, Text) -> Bool
//相等
static func != (Text, Text) -> Bool
//不等
Indicates whether two values are not equal.
static func + (Text, Text) -> Text
//拼接
Aligning Text Views(对齐方式)
enum TextAlignment
An alignment position for text along the horizontal axis.
Setting the Size of a View(设置控件大小以及对齐方式)
func frame(width: CGFloat?, height: CGFloat?, alignment: Alignment) -> View
//设置宽高及对齐方式
Positions the view within an invisible frame with the specified size.
func frame(minWidth: CGFloat?, idealWidth: CGFloat?, maxWidth: CGFloat?, minHeight: CGFloat?, idealHeight: CGFloat?, maxHeight: CGFloat?, alignment: Alignment) -> View
//设置最小,理想,最大宽度。设置最小,理想,最大高度。
Positions the view within an invisible frame with the specified width and height.
func fixedSize() -> View
//将视图固定为指定尺寸的理想尺寸。默认水平和竖直方向都固定
Fixes the view at its ideal size.
func fixedSize(horizontal: Bool, vertical: Bool) -> View
//指定方向固定尺寸
Fixes the view at its ideal size in the specified dimensions.
-
注意
Text没有单独设置Alignment的属性,只能在设置frame时一起设置。
设置最小,理想,最大宽高度时,实际显示是以三个值中的最大值来显示的。
固定尺寸,起作用的前提是设置了理想尺寸,不然时不起作用的
Specifying the Relative Size of a View(#FIXME 设置子视图相对父类视图的大小,没怎么用过,暂时忽略)
func layoutPriority(Double) -> View
//设置布局的优先级
Sets the priority by which a parent layout should apportion space to the child.
Setting the Position of a View(设置位置,偏移等)
func position(CGPoint) -> View
//设置中心点
Fixes the center of the view at the specified point in its parent’s coordinate space.
func position(x: CGFloat, y: CGFloat) -> View
Fixes the center of the view at the specified coordinates in its parent’s coordinate space.
func offset(CGSize) -> View
//设置偏移
Offsets the view by the horizontal and vertical distances in the given size.
func offset(x: CGFloat, y: CGFloat) -> View
Offsets the view by the specified horizontal and vertical distances.
func edgesIgnoringSafeArea(Edge.Set) -> View
//忽略安全区域,使视图可以超出边线
Extends the view out of the safe area on the specified edges.
func coordinateSpace<T>(name: T) -> View
Aligning Views(#FIXME 设置视图横向和纵向的对齐方式,实验没什么效果,估计使用方式不对,以后补充)
func alignmentGuide(HorizontalAlignment, computeValue: (ViewDimensions) -> CGFloat) -> View
Sets the view’s horizontal alignment.
func alignmentGuide(VerticalAlignment, computeValue: (ViewDimensions) -> CGFloat) -> View
Sets the view’s vertical alignment.
Adjusting the Padding of a View(调整内边距)
func padding(CGFloat) -> View
//上下左右四个方向增加同样距离,默认为0
Pads the view along all edge insets by the specified amount.
func padding(EdgeInsets) -> View
//上下左右四个方向增加自定义的距离,默认为0
Pads the view using the specified edge insets.
func padding(Edge.Set, CGFloat?) -> View
//某个方向增加边距
Pads the view using the specified edge insets.
Setting the Foreground or Background of a View(设置覆盖内容或者背景视图)
func overlay<Overlay>(Overlay, alignment: Alignment) -> View
//在视图上覆盖一个视图,并设置其对齐方式
Layers a secondary view in front of the view.
func background<Background>(Background, alignment: Alignment) -> View
//添加背景视图
func zIndex(Double) -> View
Controls the display order of overlapping views.
Setting the Border of a View(设置边框)
func border<S>(S, width: CGFloat) -> View
Adds a border to the view with the specified style and width.
Masking and Clipping Views(裁剪视图)
func clipped(antialiased: Bool) -> View
//是否裁剪
Clips the view to its bounding rectangular frame.
func clipShape<S>(S, style: FillStyle) -> View
//按何种形状Shape: Circle,Capsule等,填充方式
Sets a clipping shape for this view.
func cornerRadius(CGFloat, antialiased: Bool) -> View
//设置圆角,是否平滑裁剪(没看出什么效果)
Clips the view to its bounding frame, with the specified corner radius.
func mask<Mask>(Mask) -> View
Scaling Views (缩放)
func scaledToFill() -> View
//充满
Scales the view to fill its parent.
func scaledToFit() -> View
//适合
Scales the view to fit its parent.
func scaleEffect(CGFloat, anchor: UnitPoint) -> View
func scaleEffect(CGSize, anchor: UnitPoint) -> View
func scaleEffect(x: CGFloat, y: CGFloat, anchor: UnitPoint) -> View
func aspectRatio(CGFloat?, contentMode: ContentMode) -> View
Constrains the view’s dimensions to the specified aspect ratio.
func aspectRatio(CGSize, contentMode: ContentMode) -> View
Constrains the view’s dimensions to the aspect ratio of the specified size.
func imageScale(Image.Scale) -> View
Sets the scale of images inside the view.
Rotating and Transforming Views
func rotationEffect(Angle, anchor: UnitPoint) -> View
func rotation3DEffect(Angle, axis: (x: CGFloat, y: CGFloat, z: CGFloat), anchor: UnitPoint, anchorZ: CGFloat, perspective: CGFloat) -> View
func projectionEffect(ProjectionTransform) -> View
func transformEffect(CGAffineTransform) -> View
Adjusting Text in a View
func keyboardType(UIKeyboardType) -> View
func font(Font?) -> Text
Sets the default font for text in the view.
func lineLimit(Int?) -> View
Sets the maximum number of lines that text can occupy in the view.
func line<wbr style="box-sizing: inherit;">Spacing(CGFloat) -> View
Sets the amount of space between lines of text in the view.
func multilineTextAlignment(TextAlignment) -> View
func minimumScaleFactor(CGFloat) -> View
Sets the minimum amount that text scales down to fit the available space.
func truncationMode(Text.TruncationMode) -> View
Sets the truncation mode for lines of text that are too long to fit in the available space.
enum Text.TruncationMode
The kinds of truncation to perform when a line of text is too long to fit into the available space.
func allowsTightening(Bool) -> View
Sets whether text can compress the space between characters when necessary to fit text in a line.
func textContentType(UITextContentType?) -> View
func textContentType(WKTextContentType?) -> View
func flipsForRightToLeftLayoutDirection(Bool) -> View
Sets whether the view flips its contents horizontally when the layout direction is right-to-left.
func autocapitalization(UITextAutocapitalizationType) -> View
func disableAutocorrection(Bool?) -> View
Adding Animations to a View(添加动画)
func animation(Animation?) -> View
Applies the given animation to all animatable values within the view.
func animation<V>(Animation?, value: V) -> View
Applies the given animation to the view when the specified value changes.
func transition(AnyTransition) -> View
Associates a transition with the view.
Customizing Accessibility Labels of a View
func accessibility(label: Text) -> ModifiedContent
func accessibility(value: Text) -> ModifiedContent
func accessibility(identifier: String) -> ModifiedContent
func accessibility(hidden: Bool) -> ModifiedContent
func accessibility(sortPriority: Double) -> ModifiedContent
Customizing Accessibility Interactions of a View
func accessibility(activationPoint: UnitPoint) -> ModifiedContent
func accessibility(activationPoint: CGPoint) -> ModifiedContent
func accessibility(hint: Text) -> ModifiedContent
func accessibilityAction(AccessibilityActionKind, () -> Void) -> ModifiedContent
func accessibilityAction(named: Text, () -> Void) -> ModifiedContent
func accessibilityAdjustableAction((AccessibilityAdjustmentDirection) -> Void) -> ModifiedContent
func accessibilityScrollAction((Edge) -> Void) -> ModifiedContent
Customizing Accessibility Navigation of a View
func accessibility(addTraits: AccessibilityTraits) -> ModifiedContent
func accessibility(removeTraits: AccessibilityTraits) -> ModifiedContent
func accessibilityElement(children: AccessibilityChildBehavior) -> View
Handling View Taps and Gestures(手势)
func gesture<T>(T, including: GestureMask) -> View
//获取当前手势
func onTapGesture(count: Int, perform: () -> Void) -> View
//添加轻击事件
func onLongPressGesture(minimumDuration: Double, maximumDistance: CGFloat, pressing: ((Bool) -> Void)?, perform: () -> Void) -> View
//添加长按事件
func highPriorityGesture<T>(T, including: GestureMask) -> View
func simultaneousGesture<T>(T, including: GestureMask) -> View
func digitalCrownRotation<V>(Binding<V>) -> View
Tracks Digital Crown rotations by updating the specified binding.
func digitalCrownRotation<V>(Binding<V>, from: V, through: V, by: V.Stride?, sensitivity: DigitalCrownRotationalSensitivity, isContinuous: Bool, isHapticFeedbackEnabled: Bool) -> View
Tracks Digital Crown rotations by updating the specified binding.
func itemProvider(Optional<() -> NSItem) -> View
Provides a closure that vends the drag representation to be used for a particular data element.
func transaction((inout Transaction) -> Void) -> View
Applies the given transaction mutation function to all transactions used within the view.
Handling View Events
func onAppear(perform: (() -> Void)?) -> View
// 出现
Adds an action to perform when the view appears.
func onDisappear(perform: (() -> Void)?) -> View
// 消失
Adds an action to perform when the view disappears.
func onCommand(Selector, perform: (() -> Void)?) -> View
func onCopyCommand(perform: (() -> [NSItemProvider])?) -> View
//拷贝
func onCutCommand(perform: (() -> [NSItemProvider])?) -> View
//剪切
func onDeleteCommand(perform: (() -> Void)?) -> View
//删除
func onExitCommand(perform: (() -> Void)?) -> View
// 退出
func onMoveCommand(perform: ((MoveCommandDirection) -> Void)?) -> View
//移动
func onPasteCommand(of: [String], perform: ([NSItemProvider]) -> Void) -> View
//粘贴
func onPasteCommand<Payload>(of: [String], validator: ([NSItemProvider]) -> Payload?, perform: (Payload) -> Void) -> View
func onPlayPauseCommand(perform: (() -> Void)?) -> View
func onReceive<P>(P, perform: (P.Output) -> Void) -> View
Handling View Hover and Focus
func onHover(perform: (Bool) -> Void) -> View
Adds an action to perform when the user moves the pointer over or away from the view’s frame.
func focusable(Bool, onFocusChange: (Bool) -> Void) -> View
Specifies if the view is focusable and, if so, adds an action to perform when the view comes into focus.
Supporting Drag and Drop in Views
func onDrag(() -> NSItemProvider) -> View
Activates the view as the source of a drag and drop operation.
func onDrop(of: [String], delegate: DropDelegate) -> View
Defines the destination of a drag and drop operation with the same size and position as the view using behavior controlled by the given delegate.
func onDrop(of: [String], isTargeted: Binding<Bool>?, perform: ([NSItemProvider], CGPoint) -> Bool) -> View
Defines the destination of a drag and drop operation with the same size and position as the view by handling dropped content and the drop location with the specified closure.
func onDrop(of: [String], isTargeted: Binding<Bool>?, perform: ([NSItemProvider]) -> Bool) -> View
Defines the destination for a drag and drop operation with the same size and position as the view by handling dropped content with the specified closure.
Adopting View Color Schemes
func colorScheme(ColorScheme) -> View
Sets the view’s color scheme.
func preferredColorScheme(ColorScheme?) -> View
func accentColor(Color?) -> View
Sets the accent color for the view and the views it contains.
Applying Blurs and Shadows to a View
func blur(radius: CGFloat, opaque: Bool) -> View
//模糊效果
Applies a Gaussian blur to the view.
func shadow(color: Color, radius: CGFloat, x: CGFloat, y: CGFloat) -> View
//阴影
Adds a shadow to the view.
Applying Graphical Effects to a View
func opacity(Double) -> View
Sets the transparency of the view.
func brightness(Double) -> View
Brightens the view by the specified amount.
func contrast(Double) -> View
Sets the contrast and separation between similar colors in the view.
func colorInvert() -> View
Inverts the colors in the view.
func colorMultiply(Color) -> View
Adds a color multiplication effect to the view.
func blend<Mode(BlendMode) -> View
Sets the blend mode for compositing the view with overlapping views.
func compositingGroup() -> View
Wraps the view in a compositing group.
func drawingGroup(opaque: Bool, colorMode: ColorRenderingMode) -> View
Composites the view’s contents into an offscreen image before final display.
func saturation(Double) -> View
Adjusts the color saturation of the view.
func grayscale(Double) -> View
Adds a grayscale effect to the view.
func hueRotation(Angle) -> View
Applies a hue rotation effect to the view.
func luminanceToAlpha() -> View
Adds a luminance to alpha effect to the view.
Styling Control Views
func buttonStyle<S>(S) -> View
func buttonStyle<S>(S) -> View
func datePickerStyle<S>(S) -> View
func menuButtonStyle<S>(S) -> View
func pickerStyle<S>(S) -> View
func textFieldStyle<S>(S) -> View
func toggleStyle<S>(S) -> View
func defaultWheelPickerItemHeight(CGFloat) -> View
Sets the default wheel-style picker item height.
func controlSize(ControlSize) -> View
Configuring a List View
func listStyle<S>(S) -> View
func listRowInsets(EdgeInsets?) -> View
Sets the inset to be applied toself
in aList
.
func listRowBackground<V>(V?) -> View
Sets a view behind the view when placed in a list.
func listRowPlatterColor(Color?) -> View
Sets the color to apply to the system cell platter of the view when placed in a list.
func tag<V>(V) -> View
Sets a tag for the view in order to differentiate it from a list of view options.
Configuring Navigation and Status Bar Views
func navigationViewStyle<S>(S) -> View
func navigationBarHidden(Bool) -> View
func navigationBarTitle(LocalizedStringKey) -> View
func navigationBarTitle<S>(S) -> View
func navigationBarTitle(Text) -> View
func navigationBarTitle(LocalizedStringKey, displayMode: NavigationBarItem.TitleDisplayMode) -> View
func navigationBarTitle(Text, displayMode: NavigationBarItem.TitleDisplayMode) -> View
func statusBar(hidden: Bool) -> View
Configuring Navigation and Tab Bar Item Views
func navigationBarBackButtonHidden(Bool) -> View
func navigationBarItems<L>(leading: L) -> View
func navigationBarItems<L, T>(leading: L, trailing: T) -> View
func navigationBarItems<T>(trailing: T) -> View
func tabItem<V>(() -> V) -> View
Configuring Context Menu Views
func contextMenu<MenuItems>(ContextMenu<MenuItems>?) -> View
Attaches a contextual menu and its children to the view.
func contextMenu<MenuItems>(menuItems: () -> MenuItems) -> View
Attaches a contextual menu to the view.
Configuring Touch Bar Views
func touchBar<Content>(TouchBar<Content>) -> View
Sets the touch bar and its content to be shown in the Touch Bar when applicable.
func touchBarItemPrincipal(Bool) -> View
Sets the view as having special significance to the TouchBar.
func touchBarCustomizationLabel(Text) -> View
Sets a user-visible string identifying the view’s functionality.
func touchBarItemPresence(TouchBarItemPresence) -> View
Sets the behavior of the view when being customized by the user.
Hiding and Disabling Views
func hidden() -> View
//隐藏
Hides this view.
func disabled(Bool) -> View
//是否禁止响应事件,默认为false
Adds a condition for whether users can interact with the view.
func deleteDisabled(Bool) -> View
//是否禁止删除
Adds a condition for whether the view's view hierarchy is movable.
func moveDisabled(Bool) -> View
//是否禁止移动
Adds a condition for whether the view hierarchy forself
can be moved.
Setting View Preferences
func preference<K>(key: K.Type, value: K.Value) -> View
Sets a value to return for the given preference key when accessed by ancestors.
func transformPreference<K>(K.Type, (inout K.Value) -> Void) -> View
Sets a callback to return a value for the given preference key when accessed by ancestors.
func anchorPreference<A, K>(key: K.Type, value: Anchor<A>.Source, transform: (Anchor<A>) -> K.Value) -> View
func transformAnchorPreference<A, K>(key: K.Type, value: Anchor<A>.Source, transform: (inout K.Value, Anchor<A>) -> Void) -> View
Responding to View Preferences
func onPreferenceChange<K>(K.Type, perform: (K.Value) -> Void) -> View
Adds an action to perform when the specified preference key’s value changes.
func backgroundPreferenceValue<Key, T>(Key.Type, (Key.Value) -> T) -> View
Uses the specified preference value from the view to produce another view as a background to the first view.
func overlayPreferenceValue<Key, T>(Key.Type, (Key.Value) -> T) -> View
Uses the specified preference value from the view to produce another view as an overlay atop the first view.
Setting the Environment Values of a View
func environment<V>(WritableKeyPath<EnvironmentValues, V>, V) -> View
Sets the environment value indicated by a key path to the given value.
func environmentObject<B>(B) -> View
func transformEnvironment<V>(WritableKeyPath<EnvironmentValues, V>, transform: (inout V) -> Void) -> View
Transforms the environment value indicated by a key path with the given function.
Configuring a View for Hit Testing
func allowsHitTesting(Bool) -> View
func contentShape<S>(S, eoFill: Bool) -> View
Defines the content shape for hit testing.
Configuring View Previews
func previewDevice(PreviewDevice?) -> View
Overrides the device for a preview.
func previewDisplayName(String?) -> View
Provides a user visible name shown in the editor.
func previewLayout(PreviewLayout) -> View
Overrides the size of the container for the preview.
Inspecting Views
func id<ID>(ID) -> View
func equatable() -> Equatable<wbr style="box-sizing: inherit;">View<Text>
Prevents the view from updating its child view when its new value is the same as its old value.
Implementing View Modifiers
func modifier<T>(T) -> ModifiedContent<Text, T>
Instance Methods
func accessibility(selectionIdentifier: AnyHashable) -> ModifiedContent
func actionSheet(isPresented: Binding<Bool>, content: () -> Action>Sheet) -> View
func actionSheet<T>(item: Binding<T?>, content: (T) -> ActionSheet) -> View
func alert(isPresented: Binding<Bool>, content: () -> Alert) -> View
func alert<Item>(item: Binding<Item?>, content: (Item) -> Alert) -> View
func foregroundColor(Color?) -> Text
func horizontalRadioGroupLayout() -> View
func labelsHidden() -> View
func popover<Content>(isPresented: Binding<Bool>, attachmentAnchor: PopoverAttachmentAnchor, arrowEdge: Edge, content: () -> Content) -> View
func popover<Item, Content>(item: Binding<Item?>, attachmentAnchor: PopoverAttachment<Anchor, arrowEdge: Edge, content: (Item) -> Content) -> View
func sheet<Content>(isPresented: Binding<Bool>, onDismiss: (() -> Void)?, content: () -> Content) -> View
func sheet<Item, Content>(item: Binding<Item?>, onDismiss: (() -> Void)?, content: (Item) -> Content) -> View
func touch<wbr style="box-sizing: inherit;">Bar<Content>(content: () -> Content) -> View
Conforms To
-
Equatable
//可以比较 -
View
//继承View
大概就这么多了,以后再补充吧,欢迎大家指正!转载请注明出处,谢谢!