In Swiftui we have three special purpose buttons:
- EditButton
- RenameButton
- PasteButton
Let’s see how use them.
EditButton
This button is usually located in the navigation bar when a list is displayed in the view. Clicking the EditButton allows the items in the list to be displayed with delete (if onDelete is defined) and move (if onMove is defined) actions. Once you have completed your actions, tap the Done button.
Here’s the code:
struct ContentView: View {
var names = ["nicola", "tom"]
@State private var pastedText: String = ""
var body: some View {
NavigationStack {
List {
ForEach (names, id:\.self) { name in
Text(name)
}
.onDelete(perform: {_ in
})
.onMove(perform: { indices, newOffset in
})
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
}
}
}
}
Rename Button
The RenameButton is displayed (in the navigation bar) as a pencil icon and triggers the rename action.
struct ContentView: View {
var names = ["nicola", "tom"]
@State private var pastedText: String = ""
var body: some View {
NavigationStack {
List {
ForEach (names, id:\.self) { name in
Text(name)
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
RenameButton()
}
}.renameAction {
// Your code
}
}
}
}
In the rename action, you can insert the code you want.
Paste Button
With the Paste button, we can copy text or images from other apps into ours.
In the image above, I copied text from one of my posts on X.
Take a look at the code to copy text:
struct ContentView: View {
@State private var pastedText: String = ""
var body: some View {
VStack {
PasteButton(payloadType: String.self) { strings in
pastedText = strings[0]
}
Divider()
Text(pastedText)
Spacer()
}
}
}
By tapping the button, the item is pasted (in this case, a string, which is copied into a string variable).
If you want to copy and paste an image, use the following code:
import SwiftUI
import UniformTypeIdentifiers
struct ContentView: View {
@State private var image: UIImage?
var body: some View {
VStack {
PasteButton(supportedContentTypes: [UTType.image]) { info in
for item in info {
item.loadObject(ofClass: UIImage.self) { item, error in
if let img = item as? UIImage {
image = img
}
}
}
}
Divider()
Image(uiImage: image ?? .init())
}
.padding()
}
}
Happy buttons.