我正在尝试在选择视图时使用幻灯片为NSTabView的每个视图设置动画。 我有一种方式工作,但它只在我第一次选择一个新的选项卡视图时动画。之后我在切换标签视图时看不到动画,虽然我可以看到每次都触发该功能。?
override func tabView(tabView: NSTabView, didSelectTabViewItem tabViewItem: NSTabViewItem) {
tabViewItem.view!.setFrameOrigin(NSPoint(x: tabViewItem.view!.frame.origin.x + 300, y: tabViewItem.view!.frame.origin.y))
tabViewItem.view!.animator().setFrameOrigin(NSPoint(x: tabViewItem.view!.frame.origin.x - 300, y: tabViewItem.view!.frame.origin.y))
// i can see this fires every time i switch tab views but the animation only works the fist time
}
答案 0 :(得分:1)
我已经改变了一点来解决第一次问题。只需定义一个整数即可在代理中存储上一个选项卡索引。
- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem{
CABasicAnimation *controlPosAnim = [CABasicAnimation animationWithKeyPath:@"position"];
if (prevTabViewIndex>[tabView indexOfTabViewItem:tabViewItem]) {
[controlPosAnim setFromValue:[NSValue valueWithPoint:CGPointMake(tabViewItem.view.frame.origin.x - 500,tabViewItem.view.frame.origin.y)]];
} else {
[controlPosAnim setFromValue:[NSValue valueWithPoint:CGPointMake(tabViewItem.view.frame.origin.x + 500,tabViewItem.view.frame.origin.y)]];
}
[controlPosAnim setToValue:[NSValue valueWithPoint:CGPointMake(tabViewItem.view.frame.origin.x,tabViewItem.view.frame.origin.y)]];
[[tabViewItem.view layer] addAnimation:controlPosAnim forKey:@"controlViewPosition"];
[tabViewItem.view setAnimations:[NSDictionary dictionaryWithObjectsAndKeys:controlPosAnim, @"frameOrigin", nil]];
[tabViewItem.view.animator setFrameOrigin : CGPointMake(tabViewItem.view.frame.origin.x,tabViewItem.view.frame.origin.y)];
prevTabViewIndex = [tabView indexOfTabViewItem:tabViewItem];
}
答案 1 :(得分:0)
您必须确保NSTabView项具有图层支持,因此(例如,在windowDidLoad()中)调用一次:
for tabViewItem in self.tabView.tabViewItems {
if let tabViewItemView = tabViewItem.view {
tabViewItemView.wantsLayer = true
}
}
这是穆哈雷姆针对Swift的答案的更新版本,具有正确的动画偏移量:
private var previousTabViewIndex: Int = 0
public func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
guard let tabViewItem = tabViewItem,
let tabViewItemView = tabViewItem.view,
let tabViewItemLayer = tabViewItemView.layer else { return }
let animation = CABasicAnimation(keyPath: #keyPath(CALayer.position))
let tabViewIndex = tabView.indexOfTabViewItem(tabViewItem)
let origin = CGPoint(x: tabViewItemView.frame.origin.x, y: tabViewItemView.frame.origin.y)
var offsetX = self.tabView.frame.width
if self.previousTabViewIndex > tabViewIndex {
offsetX *= -1
}
animation.fromValue = NSValue(point: CGPoint(x: origin.x + offsetX, y: origin.y))
animation.toValue = NSValue(point: origin)
tabViewItemLayer.add(animation, forKey: "controlViewPosition")
self.previousTabViewIndex = tabViewIndex
}