我想要做的就是为所有状态的按钮添加背景颜色.但是我希望在tvOS故事板中使用系统按钮时保持"免费"获得的自动焦点阴影.到目前为止,我还没有找到允许这种情况的组合.
或者,我也有兴趣在按钮聚焦时以编程方式添加阴影的方法,但是没有子按钮(我还没有尝试过),我也不知道该怎么做.
您可以为自定义按钮添加阴影,如下所示:
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
context.nextFocusedView.layer.shadowOffset = CGSizeMake(0, 10);
context.nextFocusedView.layer.shadowOpacity = 0.6;
context.nextFocusedView.layer.shadowRadius = 15;
context.nextFocusedView.layer.shadowColor = [UIColor blackColor].CGColor;
context.previouslyFocusedView.layer.shadowOpacity = 0;
}
Run Code Online (Sandbox Code Playgroud)
对简单的颜色变化不满意,所以我创建了一个自定义按钮子类,看起来更像是系统按钮带来的默认动画 -
class CustomButton: UIButton
{
private var initialBackgroundColour: UIColor!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialBackgroundColour = backgroundColor
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
coordinator.addCoordinatedAnimations(
{
if self.focused
{
self.backgroundColor = UIColor.whiteColor()
UIView.animateWithDuration(0.2, animations:
{
self.transform = CGAffineTransformMakeScale(1.1, 1.1)
},
completion:
{
finished in
UIView.animateWithDuration(0.2, animations:
{
self.transform = CGAffineTransformIdentity
},
completion: nil)
})
}
else
{
self.backgroundColor = self.initialBackgroundColour
}
},
completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
没有什么太复杂,但完成工作
覆盖didUpdateFocusInContext方法并检查下一个焦点视图是否为按钮,如果是,则自定义其UI,并将其设置回orignal状态检查context.previousFocusedView是该按钮,如下所示
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
if (context.nextFocusedView == _button)
{
// set background color
}
else if (context.previousFocusedView == _button)
{
// set background color to background
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5720 次 |
| 最近记录: |