gpt4 book ai didi

swift - 如何在 cocoa 中转换 NSImageView?

转载 作者:行者123 更新时间:2023-11-30 10:28:50 26 4
gpt4 key购买 nike

我正在与 cocoa 作斗争。我正在尝试将这段动画从 iOS 写入 cocoa 。这个想法是稍微减小 NSImageView 的大小,并在动画完成后,将其再次增加到原始大小。这样看起来就好像按钮(图片)被按下一样。

@IBOutlet weak var vpnButton: NSImageView!

@objc func vpnButtonPressed(pressedGestureRecognizer: UILongPressGestureRecognizer) {
UserDefaults.standard.set(true, forKey: Constants.vpnButtonTapped)
if (pressedGestureRecognizer.state == .began) {
UIView.animate(withDuration: 0.15, animations: {() -> Void in
self.vpnButton?.transform = CGAffineTransform(scaleX: 0.965, y: 0.965)})
} else if (pressedGestureRecognizer.state == .ended) {
UIView.animate(withDuration: 0.15, animations: {() -> Void in
self.vpnButton.isHighlighted = !self.vpnButton.isHighlighted
self.vpnButton?.transform = CGAffineTransform(scaleX: 1, y: 1)})
}
}

在 cocoa 中,我能够找到 clickGesture。我不确定这是否是最好的选择。

所以我想出了这个:

@objc func vpnButtonPressed(clickedGestureRecognizer: NSGestureRecognizer) {
UserDefaults.standard.set(true, forKey: Constants.vpnButtonTapped)
print("clicked")
NSAnimationContext.runAnimationGroup({_ in
//Indicate the duration of the animation
NSAnimationContext.current.duration = 0.5
var transform = CGAffineTransform(scaleX: 0.965, y: 0.965)
self.vpnButton.layer?.setAffineTransform(transform)
}, completionHandler:{
// var transform = self.vpnButton.layer?.affineTransform()
// transform = CGAffineTransform(scaleX: 1, y: 1)
// self.vpnButton.layer?.setAffineTransform(transform!)
print("Animation completed")
})
}

通过将图像稍微移到一边,此方法仅起作用一次,但不会使其变小。如果我取消注释完成处理程序中的三行,我也看不到动画将其移回原处。

最佳答案

据我了解,您需要类似以下内容的内容(如果需要,发送操作本身超出范围 - 这里只是动画)

Cocoa custom NSImageView click animation

class MyImageView: NSImageView {

override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.wantsLayer = true
}

required init?(coder: NSCoder) {
super.init(coder: coder)
self.wantsLayer = true
}

override func mouseDown(with event: NSEvent) {
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.15
self.layer?.setAffineTransform(CGAffineTransform(scaleX: 0.965, y: 0.965))
})
}

override func mouseUp(with event: NSEvent) {
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.15
self.layer?.setAffineTransform(.identity)
})
}
}

关于swift - 如何在 cocoa 中转换 NSImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59594234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com