Modifiers
A modifier changes how a view looks or behaves. You call it on a view with a dot, and you can chain as many as you like:
Text("Hi") .font(size: 18, weight: .semibold) .color(.secondary) .padding(8) .background(.blue, radius: 6)A line that starts with . continues the expression on the line before, so
long chains can be spread over several lines. Signatures on this page use the
same notation as Views: _ means
the argument has no label, and = value is a default.
How modifiers combine
Section titled “How modifiers combine”Every modifier works on every view, built-in or your own. On a custom view, it applies to the view’s whole body.
The order of modifiers doesn’t matter. Each view has one set of settings, and each modifier fills in some of them. These two lines give the same result: a 100-point-wide box, with 10 points of padding inside it and a yellow background behind all of it:
Text("A").padding(10).frame(width: 100).background(.yellow)Text("A").background(.yellow).frame(width: 100).padding(10)Repeating a modifier replaces the earlier value, with two exceptions:
paddingadds up:.padding(4).padding(horizontal: 20)gives 4 points above and below and 24 on each side.fontandframeonly change the settings you pass:.font(size: 20).font(weight: .bold)is the same as.font(size: 20, weight: .bold).
Some settings are inherited. font, color,
textAlignment and disabled on a stack (or
any view with content) apply to everything inside it, unless a view inside
sets its own:
VStack { Text("Both lines are red and 18 points") Text("This one is bold too").font(weight: .bold)}.font(size: 18).color(.red)opacity and hidden aren’t inherited, but they
affect everything drawn inside the view. All other modifiers affect only the
view they’re on.
padding
Section titled “padding”.padding(_ amount: Float = 8, horizontal: Float, vertical: Float, top: Float, leading: Float, bottom: Float, trailing: Float)Adds empty space around the view’s content, inside its frame and background.
Text("Default").padding()Text("All sides").padding(16)Text("Sides and ends").padding(horizontal: 24, vertical: 4)Text("Two edges").padding(top: 20, leading: 40)Text("8, but 20 below").padding(8, bottom: 20)- With no arguments, every edge gets 8 points.
- With arguments, each edge takes the most specific value given: its own
edge (
top:,leading:,bottom:,trailing:), then its direction (vertical:for top and bottom,horizontal:for leading and trailing), then the unlabeledamount. Edges with no value get 0, so.padding(horizontal: 30)adds nothing above or below. - Paddings add up:
.padding(8).padding(8)is the same as.padding(16).
.font(size: Float = inherited, weight: Weight = inherited, italic: Bool = inherited, family: String = inherited)Sets the text size (in points), weight, slant and font family.
Text("Title").font(size: 24, weight: .bold)Text("Note").font(size: 11)Text("Chapter One").font(size: 20, italic: true, family: "Georgia")Text("=SUM(A1:A9)").font(family: "monospaced")- Only the parts you pass change; the rest come from the view’s container.
In a window, text starts at 14 points,
.regular. weightis one of.regular,.medium,.semibold,.bold(see Weight).familyis the name of a font family installed on the computer (seefontFamilies), or"system"for the system’s font (the one text starts with) or"monospaced"for the system’s monospaced font. A family that isn’t installed is drawn in the system’s font, so a program never fails over a missing font.italic: trueuses the family’s italic, or slants its letters when it has none.- Inherited: set it on a stack to change all the text inside.
- Icons are sized by the font size too. A
CodeEditoralways uses its own 13-point monospaced font.
.color(_ color: Color)Sets the color of text, icons, and currentColor in SVGs.
Text("Saved").color(.green)Icon(.warning).color(.orange)- The default is
.primary(near-black). See Colors for all colors. - Inherited: set it on a stack to color everything inside.
- A button’s label is blue unless
.coloris set on the button itself; a color inherited from a container doesn’t change it.
background
Section titled “background”.background(_ color: Color, radius: Float = 0)Fills the view’s whole area, padding included, with a color. radius rounds
the corners.
Text("Tag") .padding(horizontal: 8, vertical: 2) .background(.lightGray, radius: 6)- The background is drawn behind the view’s content.
- On a
Button, it replaces the button’s own gray background.
border
Section titled “border”.border(_ color: Color, width: Float = 1, radius: Float = 0)Draws a line around the view’s edge. width is the line’s thickness and
radius rounds the corners.
Text("Outlined") .padding(8) .border(.separator, width: 1, radius: 6)- The border follows the view’s outer edge (padding and frame included) and is drawn on top of the content.
- It doesn’t take up space: it’s centered on the edge, so a thick border overlaps the content a little.
.frame(width: Float?, height: Float?, minWidth: Float?, maxWidth: Float?, minHeight: Float?, maxHeight: Float?, alignment: Alignment)Controls the view’s size. All arguments are optional; pass only the ones you need, in this order.
Text("Fixed").frame(width: 120, height: 40)Button("Full width") { save() }.frame(maxWidth: .infinity)Button("OK") { save() }.frame(minWidth: 100)Text("Right").frame(maxWidth: .infinity, alignment: .trailing)| Argument | Effect |
|---|---|
width, height | A fixed size. The view is exactly this big, and no longer flexible in that direction. |
maxWidth, maxHeight | The view becomes flexible: it takes all the space it’s offered, up to this size, but never less than its content. Use .infinity for “as much as possible”. |
minWidth, minHeight | The view is never smaller than this. It still grows with its content. |
alignment | Where the content sits when the frame is bigger than it. |
- The size includes the view’s padding.
.infinityis the only shorthand for aFloat; you can write it wherever aFloatis expected, but it’s meant formaxWidth:andmaxHeight:.- Alignment.
Text,Icon,Svgand SVGImagecontent is centered in a larger frame unlessalignment:says otherwise. A stack with a frame spreads its children over the whole frame; withalignment:, it keeps its own size and sits at that position in the frame. So does the body of a view of your own, like a stack. Other views, like buttons and text fields, fill their frame. - Text wraps to fit the frame’s width.
- Giving a
widthto an SVG orImagescales the drawing to fit.
opacity
Section titled “opacity”.opacity(_ value: Float)Makes the view and everything in it see-through: 0 is invisible, 1 is
fully visible. Values outside 0…1 are clamped.
Text("Faded").opacity(0.4)An invisible view still takes up space and still responds to clicks. To
remove a view from the layout, use hidden.
hidden
Section titled “hidden”.hidden(_ isHidden: Bool = true)Hides the view when isHidden is true.
Text("Only when on").hidden(!isOn)- A hidden view takes up no space, as if it wasn’t there: stacks give it no spacing either. (In SwiftUI, a hidden view keeps its space.)
- It isn’t drawn, doesn’t respond to clicks, and its
shortcutdoesn’t run. - It is still built, so
stateinside it is kept while it’s hidden. Usingifinstead removes the view, and its state, entirely.
disabled
Section titled “disabled”.disabled(_ isDisabled: Bool = true)Turns off interaction with the view when isDisabled is true.
Button("Send") { save() }.disabled(name.isEmpty)- A disabled view ignores clicks, and its
shortcutdoesn’t run. A disabled text field can’t be edited. - Text, controls and icons in it are drawn at 40% opacity.
- Inherited: disabling a stack disables everything inside.
.onTap(_ action: fn())Runs action when the view is clicked. Usually written with a block after
the call.
Text("Click me").onTap { count += 1}- A click counts when the mouse button is pressed and released over the same view.
- Controls inside the view (buttons, toggles, text fields) handle their own
clicks; clicks on other parts of the view run
action. - On a control itself (a
Toggle,Picker,Slideror text field), the control takes the click, soactiondoesn’t run. To know when the user changes it, use the control’sonChange. - Doesn’t run while the view is disabled or hidden.
onDrag
Section titled “onDrag”.onDrag(_ action: fn(Float, Float))Runs action again and again while the mouse is moved with its button held
down, starting on the view. It gets how far the mouse moved since the last
time, across and down, in points.
Spacer() .frame(width: 6, maxHeight: .infinity) .background(.separator) .onDrag { dx, dy in sidebar = (sidebar + dx).clamped(min: 120, max: 400) }- The drag goes on until the button is released, also when the mouse leaves the view (as it does at once, with a thin bar).
- Add the movements up to follow the mouse: a width that’s dragged is
width + dx. Keep the result in bounds yourself, as withclampedabove. - Over the view, the pointer shows that it can be dragged: sideways arrows over a tall, thin view, up-and-down arrows over a wide, flat one, and a hand otherwise.
- A view with
onDragdoesn’t getonTapclicks. - Doesn’t run while the view is disabled or hidden.
onPointer
Section titled “onPointer”.onPointer(_ action: fn(PointerEvent))Runs action with everything the mouse does on the view: pressing and
letting go (any button), moving, dragging, scrolling and pinching. See
Following the mouse.
Canvas { g in g.fillCircle(x: x, y: y, radius: 6, color: .red) } .onPointer { e in if e.kind == .down || e.kind == .drag { x = e.x y = e.y } }- The block gets a
PointerEvent: what happened (kind), where (x,y, from the view’s top left corner inside its padding, andwindowX,windowY, from the window’s), how far (dx,dy), whichbutton, how manyclicks, and whethershift,altorcommandwas held. - From
.downto.up, the view has the mouse:.dragevents keep coming when the mouse leaves the view, and the.upcomes wherever it is let go. - A scroll over the view goes to it (as a
.scrollevent) rather than to aScrollaround it. - A view with
onPointerdoesn’t getonTaporonDrag. Controls on top of it (in aZStack) still get their own clicks. - Doesn’t run while the view is disabled or hidden.
.onKey(_ action: fn(String))Runs action with each key pressed while no text is being edited.
VStack { Text("Arrows move the piece")}.onKey { key in match key { "left" -> { column -= 1 } "right" -> { column += 1 } " " -> { drop() } _ -> {} }}keyis the character typed ("a","A","+"," "), or a key’s name:"enter","escape","tab","backspace","delete","left","right","up","down","home","end".- While a text field or code editor is being edited, keys go to it, not to
onKey. Keys pressed with Cmd (Ctrl on Windows) go toshortcut. - If several views have
onKey, the first one (from the top of the view tree) that is shown and enabled gets the key. - A click inside a view with
onKey(anywhere in it, except in a text field or code editor) gives it the keyboard: keys go to it rather than to the first view withonKey, until a text field or code editor is clicked. Pressing a view withonPointeralso ends text editing. Only what’s clicked counts: a click in a sheet, a popover or anything else open over the window never gives the keyboard to a view behind it; one that lands on no view withonKeyleaves the keyboard where it was. - While a view has the keyboard, keys pressed with Cmd (Ctrl on Windows)
that no
shortcuttakes come to it too, as"cmd+c"or"cmd+shift+k". Cmd+Z and Cmd+Shift+Z stay undo and redo. - While a view has the keyboard, a code editor whose
line:changes only scrolls to it, without taking the keyboard. - When some view has
onKeyEvent, keys go there instead.
onKeyEvent
Section titled “onKeyEvent”.onKeyEvent(releases: Bool = false, _ action: fn(KeyEvent))Like onKey, with the modifier keys held: runs action with a
KeyEvent for each key pressed while no text
is being edited.
Canvas { g in drawMap(g) } .onKeyEvent { e in let step = if e.shift { 100.0 } else { 10.0 } match e.key { "left" -> { panX -= step } "right" -> { panX += step } "z" -> { if e.command && e.shift { redo() } else if e.command { undo() } } _ -> {} } }-
e.keyis the key without the modifiers ("a"for Shift+A,"1"for Shift+1) or a key’s name:"enter","escape","tab","space","backspace","delete","left","right","up","down","home","end","pageup","pagedown","insert","f1"…"f12". -
e.textis what the key types ("A"for Shift+A), or""for keys that type nothing, like the arrows. -
e.shift,e.alt,e.commandande.controlsay which modifier keys were held.commandis Cmd on macOS and Ctrl on Windows and Linux (the key shortcuts use);controlis the Ctrl key itself, on every system. -
e.repeatedis true for the presses a key held down sends after the first. -
With
releases: true,actionalso runs when a key is let go (withe.uptrue), and for the modifier keys pressed and let go on their own (e.keyis"shift","alt","control"or"command"). That’s for what’s done while a key is held, like panning while Space is down:.onKeyEvent(releases: true) { e inif e.key == "space" && !e.repeated {panning = !e.up}} -
shortcuts come first: a key with Cmd that a shortcut takes doesn’t come here. Keys with Cmd that no shortcut takes do. -
While a text field or code editor is being edited, keys go to it, not to
onKeyEvent. -
If several views have
onKeyEvent, the first one (from the top of the view tree) that is shown and enabled gets the key. When a view hasonKeyEvent, no view’sonKeygets keys. -
A click inside a view with
onKeyEventgives it the keyboard, as foronKey: keys go to it rather than to the first view withonKeyEvent, until a text field or code editor is clicked. So two canvases side by side, each with its ownonKeyEvent, each get the keys after a click in them. A click in a sheet or popover doesn’t reach views behind it.
cursor
Section titled “cursor”.cursor(_ style: CursorStyle)The pointer shown while the mouse is over the view.
Text("Read more").color(.blue).cursor(.hand).onTap { open() }style is one of .arrow, .hand, .crosshair, .grab, .grabbing,
.text, .move, .wait, .notAllowed, .resizeHorizontal,
.resizeVertical, .zoomIn, .zoomOut (see
CursorStyle). The innermost view under
the mouse that has a cursor decides.
.id(_ value: Int or String)Gives the view an identity of its own, instead of its position among its siblings.
for item in items { Text(item.name).id(item.id)}Tessel keeps each view’s state, text field focus and undo history by
identity. By default the identity is the view’s position, so if a list is
reordered, the state stays at the old positions. With .id(…), the state
follows the item. The value must be an Int or a String, and should be
unique among the views next to it. See Lists.
.tag(_ value: T)Marks an option in a Picker or a page in a
TabView. value must have the same type as
the picker’s or tab view’s selection.
Picker(selection: mode) { Text("List").tag(Mode.list) Text("Grid").tag(Mode.grid)}.tag is only allowed on the views directly inside a Picker or TabView
block; anywhere else it’s an error.
shortcut
Section titled “shortcut”.shortcut(_ key: String, action: fn())Runs action when the user presses Cmd + key (Ctrl + key on Windows).
The action is usually a block after the call.
Button("Save") { save() } .shortcut("s") { save() }keyis one character that isn’t an uppercase letter or whitespace, like"s","1"or",". The key names"enter","escape","tab","backspace","delete","left","right","up","down","home"and"end"work too.- Put
shift+oralt+(or both) before the key to need Shift or Alt (Option) as well:"shift+z","alt+shift+s". A shortcut without them also runs with them held, unless another shortcut asks for exactly those keys: with both"z"and"shift+z", Shift+Cmd+Z runs the second. only+at the start leaves Cmd (Ctrl) out, for a shortcut with the Ctrl key or Alt instead:"only+control+g"is Ctrl+G on every system, and"only+alt+left"is Alt+Left. It needscontrol+oralt+. See Shortcuts without Cmd.- Any other key, such as
"F5","S"or"cmd+s", is an error. Don’t write Cmd or Ctrl: it’s added for you. - A view can have several shortcuts; each
.shortcutadds one. - The shortcut works only while its view is shown and enabled. In a
TabView, only the shortcuts on the selected page work. - The shortcut belongs to the view it’s on, not to a button: attaching it to a button doesn’t press the button. Put the same code in both, or call one function from both.
- While text is being edited, Cmd+A, Cmd+C, Cmd+X, Cmd+V and Cmd+Z keep their editing meaning.
- If several views have the same shortcut, the first one (from the top of the view tree) runs.
onAppear
Section titled “onAppear”.onAppear(_ action: fn())Runs action once when the view appears.
Text("{count} files").onAppear { count = listFolder(currentFolder())?.count ?? 0}- “Appears” means the view is there now but wasn’t in the previous update:
when the app starts, or when an
ifor aforloop adds it. If the view goes away and comes back,actionruns again. A view made invisible with.hidden()is still there, so hiding and showing it doesn’t runaction. - It runs before the view is first drawn. It may change
state; the screen is then updated before anything is drawn.
onSubmit
Section titled “onSubmit”.onSubmit(_ action: fn())On a TextField: runs action when the user
presses Enter while editing it.
TextField("New item", text: name) .onSubmit { save() }Enter also stops editing the field. (In a CodeEditor, Enter starts a new
line instead, so .onSubmit doesn’t apply.)
onFieldKey
Section titled “onFieldKey”.onFieldKey(_ action: fn(String))On a one-line TextField: runs action with
the keys the field has no use for, while it’s edited. That’s for a field
that goes with a list or a search, like the IDE’s Quick Open box and its
find bar.
TextField("Go to file", text: query) .onFieldKey { key in match key { "down" -> { choice += 1 } "up" -> { choice -= 1 } "enter" -> open(choice) "escape" -> close() _ -> {} } }keyis"up","down","escape","enter"or"shift+enter".- Enter comes here only when the field has no
.onSubmit; Shift+Enter always does. - The field stays edited: the keyboard doesn’t leave it. Escape doesn’t
stop editing it, or close a popover it’s in;
actiondoes what’s needed, like closing the box (andstartEditinggives the keyboard to another field).
tabItem
Section titled “tabItem”.tabItem(_ title: String)The title of a page’s tab in a TabView. Pages
without one are titled “Untitled”.
TabView(selection: tab) { Text("Welcome!").tabItem("Home").tag("home")}autofocus
Section titled “autofocus”.autofocus()On a TextField or
CodeEditor: starts editing it as soon as it
appears, so the user can type right away.
TextField("Search", text: name).autofocus()It takes effect when the view appears (see onAppear), not
on every update. If several views appear with .autofocus() at the same
time, the last one gets the focus.
animation
Section titled “animation”.animation(_ seconds: Float = 0.25, curve: Curve = .easeInOut)Changes to the view, and to the views inside it, take seconds to happen
instead of happening at once: a view moves and resizes to its new place, its
opacity and background color change gradually,
a view that appears fades in, and one that disappears fades out.
VStack { Text("Details").frame(height: if expanded { 120 } else { 24 }) Button("More") { expanded = !expanded }}.animation()- Inherited: it covers everything inside the view.
.animation(0)turns it off again for a part. - A change starts slowly, speeds up and slows down at the end;
curve:picks another way, like.spring(seeCurve). A change that comes while another is under way starts from where the view is. - A view that disappears fades out where it was, as it last looked. Scrolling and resizing the window are never animated.
- Views are told apart by their position, or by
.id: give the views of a list an id so that the right ones move when one is added or removed. - Clicks go to where a view will end up, not to where it’s drawn on the way.
offset
Section titled “offset”.offset(x: Float = 0, y: Float = 0)Shows the view (and everything in it) that far from where layout put it, without moving anything else.
Text("3").background(.red, radius: 8).offset(x: 10, y: -6)- The space the view takes in its stack stays where it was; only the view is shifted. It may end up over its neighbors, or outside its container.
- Clicks go to where the view is shown.
- Unlike
padding, changing an offset doesn’t change any view’s size, so aCanvas(redraw:)that’s shifted keeps its drawing.
clipped
Section titled “clipped”.clipped(_ isClipped: Bool = true)Nothing of what’s in the view shows outside its frame.
ZStack { Image("photo.jpg").offset(x: panX, y: panY)}.frame(width: 240, height: 160).background(.black, radius: 12).clipped()- The corners follow the view’s
backgroundorborderradius, so content can be given rounded corners. - What’s cut away doesn’t get clicks either.
onResize
Section titled “onResize”.onResize(_ action: fn(Float, Float))Runs action with the view’s width and height (inside its padding) when it
is first laid out, and again whenever its size changes.
Canvas { g in drawMap(g) } .onResize { width, height in mapWidth = width mapHeight = height }It may change state; the views are then built and laid out again before
anything is drawn.
onDrop
Section titled “onDrop”.onDrop(_ action: fn(String))Runs action with the path of each file dropped on the window.
VStack { Text(if path.isEmpty { "Drop a file here" } else { path.fileName })}.onDrop { dropped in path = dropped }The window is one place to drop on: the first view (from the top of the
view tree) with onDrop that is shown and enabled gets the files, wherever
in the window they land. Several files dropped together arrive one by one.
To drag views inside the app, see draggable.
draggable
Section titled “draggable”.draggable(_ payload: String)The view can be dragged with the mouse onto a view with
dropTarget, which gets payload. See
Reordering by dragging.
Text(layer.name).draggable(layer.id)- The drag starts once the mouse has moved a few points with the button
held; a press that doesn’t move is still a click (for an
onTapor a button in the view). - While it’s dragged, a see-through copy of the view follows the mouse. Escape cancels the drag.
- The payload is a
String: usually an id, or a few values joined together, that tells the drop target what’s coming. - A view with
onPointergets the mouse first, so it can’t also be dragged this way. Doesn’t work while the view is disabled or hidden.
dropTarget
Section titled “dropTarget”.dropTarget(isTargeted: bind Bool = …, _ action: fn(String, Float, Float))Runs action when a view with draggable is dropped on this
one, with its payload and where it was dropped (x, y, from this view’s
top left corner inside its padding). The action is usually a block after the
call.
HStack { Text(name) } .background(if targeted { .highlight } else { .clear }) .dropTarget(isTargeted: targeted) { payload, x, y in moveLayer(payload, before: index) }isTargeted:is bound to aBoolthat is true while something is dragged over the view, so it can show where the drop will go. Bind it to astateof a custom view to give each row of a list its own.- When drop targets are inside each other, the innermost one under the mouse gets the drop.
- Doesn’t work while the view is disabled or hidden.
contextMenu
Section titled “contextMenu”.contextMenu(_ items: View)A menu that opens where the view is right-clicked (or Ctrl-clicked, on
macOS). Its items are MenuItems,
MenuDividers and submenus
(Menu).
Text(layer) .contextMenu { MenuItem("Rename…") { rename(layer) } MenuDivider() MenuItem("Remove") { remove(layer) } }- The menu is drawn in the window, over everything. Arrow keys, Enter and Escape work in it; a click outside closes it.
- Shortcuts of its items are only shown.
- On a view with
onPointertoo, the right button opens the menu and the others go toonPointer.
See Context menus.
menuBar
Section titled “menuBar”.menuBar(_ items: View)The app’s menus, each a Menu: the menu bar at
the top of the screen on macOS (with the app, Edit and Window menus Tessel
adds), drawn at the top of the window on Windows.
VStack { … } .menuBar { Menu("File") { MenuItem("Open…", shortcut: "cmd+o") { open() } MenuItem("Save", shortcut: "cmd+s") { save() }.disabled(!edited) } }Put it on any view of the main window; the first one that has it counts. The items’ shortcuts work wherever the keyboard focus is. See The menu bar.
statusBar
Section titled “statusBar”.statusBar(_ items: View)A bar along the bottom of the window, across its whole width, under the rest
of the window’s content, which gets the room above it. Its items are any
views, in a row like an HStack’s, from the
leading end.
VStack { … } .statusBar { Text("{features.count} features") Spacer() Text("Zoom {zoom}%") }- A
Spacerpushes the items after it to the trailing end. - The bar is as tall as its tallest item, and at least 24 points; its items are 12 points apart, 8 points from its ends, and centered up and down.
- Its text is 11 points, in the secondary color, on a light gray background
(dark gray in the dark appearance) with a thin line over it. An item’s own
.fontor.colorchanges that for it. - Put it on any view of a window; a
Windowhas its own. When several views in one window have it, the first one counts (a view comes before the views inside it). One on a hidden view doesn’t count. - In a test script,
treeanddumpshow the bar asStatusBar, after the window’s other views.
See The status bar.
popover
Section titled “popover”.popover(isPresented: bind Bool, edge: Edge = .bottom, content: View)Shows content next to the view, over the rest of the window, while
isPresented is true.
Button("Style…") { showStyle = true } .popover(isPresented: showStyle) { Toggle("Dashed", isOn: dashed) }edgeis the side it shows on:.bottom,.top,.leadingor.trailing. When there’s no room there, it goes on the other side; it always stays in the window.- A click outside it, or Escape, closes it, setting
isPresentedtofalse.
See Popovers.
.sheet(isPresented: bind Bool, content: View)Shows content in a card in the middle of the window while isPresented is
true. The rest of the window is dimmed and takes no clicks until the
sheet closes.
Button("New…") { creating = true } .sheet(isPresented: creating) { VStack { TextField("Name", text: name) Button("Create") { dismiss() } } .frame(width: 280) }dismiss(), Escape, or settingisPresentedtofalsecloses it. A click outside it doesn’t.- It’s as large as its content.
See Sheets.
onOpenFile
Section titled “onOpenFile”.onOpenFile(_ action: fn(String))Runs action with the path of each file the system asks the app to open:
opened with the app in Finder, dropped on its Dock icon, or the one it was
started to open (on Windows: files it’s started with).
VStack { … } .onOpenFile { path in open(path) }The first view of the main window with onOpenFile that’s shown and enabled
gets the files; files that come before there’s one wait for it. List the
extensions in the app’s documentTypes: for the
system to offer the app for them. See
Opening documents.
onCloseRequest
Section titled “onCloseRequest”.onCloseRequest(_ action: fn())Runs instead of closing when the user closes the window or quits the app.
The window stays open until the app calls
closeWindow() or
quit().
VStack { … } .onCloseRequest { if edited { askToSave = true } else { quit() } }On the main window, it also decides what quitting does. In a
Window, it decides for that window. See
Asking before closing.
tooltip
Section titled “tooltip”.tooltip(_ text: String)A short text that shows next to the pointer when the mouse rests on the view for a moment.
Icon(.trash).onTap { remove() }.tooltip("Delete the selected rows")It goes away when the mouse leaves the view, and on a click, a key or a scroll. An empty text shows nothing.
A tooltip is also what a screen reader calls a view that has no words of
its own (see accessibilityLabel).
accessibilityLabel
Section titled “accessibilityLabel”.accessibilityLabel(_ text: String)What a screen reader (VoiceOver on macOS, Narrator on Windows) calls the view. Controls with a title are called by it already; this is for the ones without words, or with words that only make sense to someone looking:
Icon(.trash).onTap { remove() }.accessibilityLabel("Delete the selected rows")Slider(value: volume, from: 0, to: 1).accessibilityLabel("Volume")See Accessibility.
hoverBackground
Section titled “hoverBackground”.hoverBackground(_ color: Color, radius: Float = 0)A background that’s shown only while the mouse is over the view. radius
rounds the corners.
Text("files") .padding(4) .onTap { save() } .hoverBackground(.lightGray, radius: 4)It’s drawn on top of a normal background.
Any view can have a hover background. If views with hover backgrounds are nested, only the innermost one under the pointer shows it.
textAlignment
Section titled “textAlignment”.textAlignment(_ alignment: Alignment)Lines up the lines of multi-line text inside the text’s own box: .leading
(the default), .center or .trailing.
Text("Welcome to Tessel.\nLet's build something.") .textAlignment(.center)- Only the horizontal part of the alignment counts:
.topTrailingacts like.trailing, and.topor.bottomlike.center. - It doesn’t move the text’s box. Where the box goes is up to its stack’s
alignment:or its frame’s. - Inherited: set it on a stack to align all the text inside.
rotation
Section titled “rotation”.rotation(_ degrees: Float)Turns the view (and what’s in it) clockwise around its middle. It takes the room of the box around it as it shows, so the views around it move to make room; clicks follow its shape.
Icon(.arrowUp).rotation(heading).scale(_ factor: Float = 1, x: Float = 1, y: Float = 1)Makes the view larger or smaller around its middle: across by
factor * x, down by factor * y. .scale(2) doubles it;
.scale(x: -1) mirrors it. Like .rotation, it takes the room of its new
size.
trayIcon
Section titled “trayIcon”.trayIcon(_ icon: IconName, title: String = "", keepRunning: Bool = false, items: View)The app’s icon in the menu bar (macOS) or the taskbar’s tray (Windows),
with a menu of MenuItems, MenuDividers and Menus. title shows beside
it (macOS) or as its tooltip (Windows). With keepRunning, closing the
main window hides it and the app goes on; showWindow() brings it back.
See The desktop.
dragFile
Section titled “dragFile”.dragFile(_ path: String)The view can be dragged out of the app as the file at path: onto the
desktop, into a folder, or into another app. See
Dragging files out.
lineLimit
Section titled “lineLimit”.lineLimit(_ lines: Int)Shows at most lines lines of text. When there’s more, the last line
ends in ”…” where it’s cut.
Text(path).lineLimit(1)- It counts the lines the text wraps onto, and those
\nstarts. - Inherited: set it on a stack to limit every text inside.
0is no limit. - A selectable text that’s cut short selects and copies what shows.
selectable
Section titled “selectable”.selectable(_ isSelectable: Bool = true)The text can be selected with the mouse (a double click picks a word, a triple click all of it) and the keyboard (Shift with the arrows), and copied with Cmd+C (Ctrl+C on Windows). It can’t be changed.
Text("Error 4417: the file is locked").selectable()- Inherited: set it on a stack to make every text inside selectable;
.selectable(false)on one inside takes it away. - A text with
.onTapor.onPointertakes clicks for those instead.
gridCellColumns
Section titled “gridCellColumns”.gridCellColumns(_ count: Int)In a GridRow: the cell takes
count columns, the next cell starting after them.
gridColumnAlignment
Section titled “gridColumnAlignment”.gridColumnAlignment(_ alignment: Alignment)In a GridRow: lines up the cells of
the cell’s whole column across: .leading, .center or .trailing (only
the horizontal part counts). One cell of the column is enough. A cell over
several columns lines up as it says itself.