SwiftUI中如何将已导入的logo图片设置为可点击按钮?
解决方法
直接把你已经配置好样式的Image("logo1024")视图放到Button的label闭包中,替换掉原有测试用的Text即可,不需要引入额外依赖或者自定义手势。
修改后的可运行代码:
struct ContentView: View { var body: some View { VStack { Group{ // Logo可点击按钮 Button(action: { print("logo tapped!") }, label: { Image("logo1024") .resizable() .padding() .frame(width: 120, height: 120) // 可选:保证设置的120*120全范围都响应点击,避免透明padding区域点击无反应的问题 .contentShape(Rectangle()) }) // 不需要保留原绿色加号按钮的话,直接删掉下面这段Button代码即可 Button(action: { print("add button tapped!") }, label: { Text("+") .foregroundColor(.white) .frame(width: 40, height: 40) .background(Color.green) .cornerRadius(15) .padding() }) }.frame(maxHeight: .infinity, alignment: .bottom) } } }
可选优化
- 如果不需要系统默认的按钮点击高亮效果,可以给按钮加
.buttonStyle(.plain)修饰符 - 如果需要自定义按压交互效果,可以基于
ButtonStyle协议编写自定义样式,适配自身设计需求
内容的提问来源于stack exchange,提问作者JuicyKevin
相关产品推荐
相关产品推荐

