SwiftUI按钮按下无高亮需长按1秒才显示问题求助
解决SwiftUI按钮需长按才高亮的问题
问题:按钮按下时希望立刻显示高亮效果,但当前必须长按至少1秒才会出现高亮,相关代码如下:
原ContactsView代码
ZStack { Color.backgroundColor.ignoresSafeArea() VStack(spacing: .zero) { HStack { Image(uiImage: UIImage(data: contactImage ?? Data()) ?? UIImage()) .resizable() .scaledToFill() .frame(width: 50, height: 50) .clipShape(Circle()) .overlay(Circle().stroke(Color.white, lineWidth: 4)) .padding(.leading, .large) Text(contactName ?? "") .foregroundStyle(.white) .fontWeight(.heavy) Spacer() Button { print("Share code") } label: { Text("Add friend") .padding(.medium) .background(Color.white) .cornerRadius(16) .padding(.horizontal, .large) .foregroundColor(.black) } } } .frame(maxWidth: .infinity, alignment: .leading) }
原使用方式代码
ScrollView { ForEach(viewModel.getContacts, id: \.id) { contact in VStack(spacing: .zero) { ContactsView(contactImage: contact.thumbnail ?? Data() , contactName: contact.fullName ?? "") } .padding(.vertical, .large) } }
解决方法
核心原因
ScrollView为避免滑动时误触按钮,默认给子视图的触摸事件添加了延迟,导致按钮需要长按才触发高亮。
方案1:自定义ButtonStyle实现即时高亮
手动处理按钮按下状态的高亮效果,绕过系统延迟:
// 定义自定义按钮样式 struct ImmediateHighlightButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .background(configuration.isPressed ? Color.white.opacity(0.8) : Color.white) .cornerRadius(16) .animation(.easeInOut(duration: 0.1), value: configuration.isPressed) } } // 修改ContactsView中的Button,应用样式 Button { print("Share code") } label: { Text("Add friend") .padding(.medium) .padding(.horizontal, .large) .foregroundColor(.black) } .buttonStyle(ImmediateHighlightButtonStyle())
方案2:提高按钮手势优先级
让按钮的点击手势优先于ScrollView的滑动手势:
Button { print("Share code") } label: { Text("Add friend") .padding(.medium) .background(Color.white) .cornerRadius(16) .padding(.horizontal, .large) .foregroundColor(.black) } .highPriorityGesture(TapGesture())
方案3:取消整个ScrollView的触摸延迟
如果希望ScrollView内所有子视图都取消触摸延迟,可直接修改ScrollView:
ScrollView { // 原有内容 } .delayTouches(false)
内容的提问来源于stack exchange,提问作者Exal
相关产品推荐
相关产品推荐

