【问题标题】:Clipped Image calls TapAction outside frameClipped Image 在框架外调用 TapAction
【发布时间】:2019-11-22 15:11:06
【问题描述】:

我有一个关于图像上的 tapAction 的问题。 TapAction 闭包在不应该发生的剪切区域上被调用。我该怎么办?

Image(uiImage: image)
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(height: 200, alignment: .center)
    .presentation(tapped ? Modal(Image(uiImage: image)) : nil)
    .clipped()
    .cornerRadius(10)
    .border(Color.black, width: 2, cornerRadius: 10)
    .tapAction {
        self.tapped.toggle()
    }

结果如下:

【问题讨论】:

标签: swift image swiftui


【解决方案1】:

更新

我更新了我的答案。这是正确的做法。有一个名为contentShape() 的修饰符可以用来定义命中测试区域:

import SwiftUI

struct ContentView: View {
    @State private var tapped = false

    var body: some View {
        Image(systemName: "circle.fill")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .frame(height: 200, alignment: .center)
            .presentation(tapped ? Modal(Image(systemName: "photo")) : nil)
            .clipped()
            .cornerRadius(10)
            .border(Color.black, width: 2, cornerRadius: 10)
            .contentShape(TapShape())
            .tapAction {
                self.tapped.toggle()
            }
    }

    struct TapShape : Shape {
        func path(in rect: CGRect) -> Path {
            return Path(CGRect(x: 0, y: 0, width: rect.width, height: 200))
        }
    }
}

【讨论】:

  • 天哪,谢谢?我已经尝试了很多,但这是完美的
  • 我之前尝试过的是有一个 RoundedRectangle,它的背景是图像,但没有任何改变
  • 嗨@jsbeginnerNodeJS,我更新了我的答案。事实证明,有一种正确的方法可以做到这一点,而无需诉诸 .opacity(0.00001)。
  • 哦,我一直在寻找解决方案。谢谢!每当我们使用clipped/masked 时,必须总是调用contentShape 真的感觉很奇怪,这样触摸就不会在外面注册。还有“反向”——图像的不可见部分可能会“覆盖”一个不再起作用的相邻按钮(我的实际问题)......我已经想念clipsToBounds
  • 谢谢!这让我免于沮丧。
猜你喜欢
  • 2012-10-06
  • 2013-04-03
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多