- 可以对比参照UIKit中的UIView
- 了解swift的人都知道,swift是一门基于协议的语言,同样swiftUI也是,与UIKit不同的是,View并不是一个视图,不具有初始化方法,它是一个协议,swiftUI中所有的元素都遵循这个协议,所以view是swift的基础。它的一些方法,以后介绍到的内容都适用。
所以当你看到下面的方法时,第一反应是设置背景视图,其实你并不想这么做,只是想设置一个背景颜色,但是你找了半天也没找到backgroundColor。开始我也懵逼,后来找了Color发现,遵循View协议,所以在这里直接用Color就好了
func background<Background>(Background: View)
下面就介绍一下它的方法,更多详细事例可以参阅官方文档
Implementing a Custom View
var body: Self.Body
The content and behavior of the view.
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.
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
struct ViewDimensions
A view’s size and its alignment guides in its own coordinate space.
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.
protocol AlignmentID
Types used to identify alignment guides.
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.
struct EdgeInsets
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 foregroundColor(Color?) -> View
//对比UIKit中tintColor
Sets the color that the view uses for foreground elements.
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.
enum ContentMode
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
{ } Creating Accessible Views
Make your app accessible to everyone by applying accessibility modifiers to your SwiftUI views.
func accessibility(label: Text) -> ModifiedContent
func accessibility(value: Text) -> ModifiedContent
func accessibility(identifier: String) -> ModifiedContent
func accessibility(hidden: Bool) -> ModifiedContent
Accessibility Modifier Types
A set of types used to improve a view’s comprehensibility, interactivity, and navigability.
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
func accessibility(sortPriority: Double) -> ModifiedContent
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
struct SubscriptionView
A view that subscribes to a publisher with an action.
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.
struct DropInfo
The current state of a drop.
struct DropProposal
The behavior of a drop.
enum DropOperation
Operation types that determine how a drag and drop session resolves when the user drops a drag item.
protocol DropDelegate
An interface that you implement to interact with a drop operation in a view modified to accept drops.
Adopting View Color Schemes
func colorScheme(ColorScheme) -> View
Sets the view’s color scheme.
enum ColorScheme
The possible types of color schemes, like Dark Mode.
func preferredColorScheme(ColorScheme?) -> View
struct PreferredColorSchemeKey
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.
enum BlendMode
func drawingGroup(opaque: Bool, colorMode: ColorRenderingMode) -> View
Composites the view’s contents into an offscreen image before final display.
enum ColorRenderingMode
The working color space for color-compositing operations.
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
enum ControlSize
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
struct NavigationBarItem
A configuration for a navigation bar that represents a view at the top of a navigation stack.
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.
struct ContextMenu
A container for views that you present as a menu items in a contextual menu in response to the standard system gesture.
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>
struct ModifiedContent
struct EmptyModifier
The empty, or identity, modifier.
Instance Methods
func accessibility(selectionIdentifier: AnyHashable) -> ModifiedContent
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 touchBar<Content>(content: () -> Content) -> View
转载请注明出处,谢谢!