How to make Text tappable area exand?

Hi

I am writing a view that the user to select a value from a list as they fill in a calling view, and at the trailing edge of each row in the list is a button that allows the user to change the value in the list:

I started with this code

List {
    ForEach(getResults(), id: \.objectID) { item in
        HStack {
            Text(itemValue(item: item))
                .onTapGesture {
                    onAccept(item)
                    dismiss()
                }
            Spacer()
            Button(action: { currentItem = item }) {
                Image(systemName: "square.and.pencil")
            }
        }
    }
}

The trouble with it is that the button to the right which brings up the view for renaming is expected to be used rarely, and the main purpose of this list is to select a value from the list. However, the tappable area of the Button includes the whole free space row, while the tappable area of the Text is just the extent of the visible text, the reverse of what I want.

I got the desired behaviour by switching view types and forcing the font colours to be what they were in the first code:

HStack {
     Button(itemValue(item: item)) {
        onAccept(item)
        dismiss()
    }
     .foregroundColor(.primary)
    Spacer()
    Image(systemName: "square.and.pencil") 
        .foregroundColor(.accentColor)
        .onTapGesture {
            currentItem = item
        }
}

Is there a way to get the desired tappable areas with the view types I wanted at first and thus to avoid overriding the foreground colour ?

  • I don't understand "to avoid overriding the foreground colour ?". What is the link with the tap effect ?

  • Claude31: Notices that in the working version, the second one, I am using the modifier .foregroundColor on both the Button and the Image. That allows me to use the expanded tappable area that Buttons offer. In the second one, Button effectively occupies all the available space after the Image and Spacer have been allocated their minimal required space. In the first code block, the Text and Spacer are allocated their space and the Button takes up what it left.

    It just seems counter-intuitive to be giving a Button the colour of a Text, and an Image the colour of a Button.

Add a Comment