1

I'm using SwiftUI and create a SlideMenu, I want to rename my menu item. I do it by change Text to TextField but the TextField disabled by default. What wrong with TextField, I unable to click on it or is there any way to rename without swap Text <-> TextField?

SlideMenu

    struct CellView: View {
    @State private var isRename = false
    @State private var newName: String = ""
    var menuItem: MenuItem
    var body: some View {
        HStack {
            Image(systemName: "folder")
                .foregroundColor(.accentColor)
            if isRename {
                TextField(menuItem.name ?? "Unknow name", text: $newName)
            }else {
                Text(menuItem.name ?? "Unknow name")
            }
            Spacer()
        }        
        .contextMenu {
            Button(action: {
                isRename = true
            }) {
                HStack {
                    Image(systemName: "pencil")
                        .foregroundColor(.accentColor)
                    Text("Rename")
                }
            }
        }
    }
}
Trung Phan
  • 923
  • 10
  • 18

2 Answers2

0

I don't think it is disabled (as tested provided code), you just see placeholder and TextField is not in focus by default.

So here is possible solution (based on CustomTextField from this answer)

    if isRename {
         CustomTextField(text: $newName,
                nextResponder: .constant(nil),
                isResponder: .constant(true),
                isSecured: false,
                keyboard: .default)
    }else {
        Text(menuItem.name ?? "Unknow name")
    }
    Spacer()
}        
.contextMenu {
    Button(action: {
        newName = menuItem.name ?? "Unknown name"
        isRename = true
    }) {

Note: it is not shown what is MenuItem but consider possibility to bind text field directly to menuItem.name

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you for your help, It can click but very hard, I think this is a bug from the beta version. BTW I write this app for Mac but your suggestions really help. If Apple does not fix it in October I will try to use NSTextField. – Trung Phan Jul 29 '20 at 08:42
0

With iOS 16, there's a built-in RenameButton view and a .renameAction{} modifier:

RenameButton()
.renameAction {
   //add action here
 }
AnupamChugh
  • 1,779
  • 1
  • 25
  • 36