gpt4 book ai didi

ios - UIView 和 UIButton 的动画区别

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:01:42 26 4
gpt4 key购买 nike

在我的自定义表格 View 单元格中,我有 4 个带有动画的按钮(如下所示)。问题是当我使用 UIButton 时,动画没有按我想要的方式播放。但是当我使用 UIView 时,它完全按照我想要的方式工作。

代码完全相同,只是使用了不同类型的UIView

这个动画使用了一个UIButton:

Animation with a button

此动画使用的是 UIView

Animation with a UIView

为了让事情更清楚一点,我在代码中唯一替换的是:

// Test with Buttons
let button1 = Button() // Subclass of UIButton
let button2 = Button()

// Test with UIViews
let button1 = UIView()
let button2 = UIView()

问题:
谁能告诉我为什么 UIButton 的行为与普通 UIView 不同?


最初我想通过不发布代码,我可以让问题更容易阅读,因为两个测试都使用完全相同的代码(除了“元素”(元素是 UIViewUIButton),并认为问题可能在于“元素”之间的差异。我现在意识到这是我的错误。

我的代码:

class CustomView: UIView {

private var base: [NSLayoutConstraint] = []
private var open: [NSLayoutConstraint] = []

var buttons: [UIView] = []

private var active = false

override init(frame: CGRect) {
super.init(frame: frame)

let button1 = CustomButton(frame: CGRectZero, color: UIColor.yellowColor().CGColor)
let button2 = CustomButton(frame: CGRectZero, color: UIColor.redColor().CGColor)

// let button1 = UIView(); button1.backgroundColor = UIColor.yellowColor()
// let button2 = UIView(); button2.backgroundColor = UIColor.redColor()

let views = ["button1": button1, "button2": button2]

buttons = [button1, button2]

buttons.enumerate().forEach {
$0.element.translatesAutoresizingMaskIntoConstraints = false
addSubview($0.element)

addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button\($0.index + 1)]|", options: [], metrics: nil, views: views))

base += [NSLayoutConstraint(item: $0.element, attribute: .Width , relatedBy: .Equal, toItem: buttons.first!, attribute: .Width , multiplier: 1, constant: 0)]
}

open += [NSLayoutConstraint(item: buttons.last!, attribute: .Width, relatedBy: .Equal, toItem: buttons.first!, attribute: .Width, multiplier: 0.33, constant: 0)]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[button1]-0.5-[button2]|", options: [], metrics: nil, views: views))
addConstraints(base)

backgroundColor = .blackColor()
clipsToBounds = true
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

func changeState() {
removeConstraints(active ? open : base); addConstraints(active ? base : open)

active = !active

UIView.animateWithDuration(0.5, animations: { self.layoutIfNeeded() })
}
}

解决方案:
在发布代码并不小心更改了按钮的背景颜色后,我注意到它的行为是相应的。这让我意识到我在按钮中使用了 CAShapeLayer,这导致了第一个动画中看到的行为。现在我知道要解决什么了。如果这篇文章应该被关闭或删除,请告诉我。然后我会删除答案。并感谢那些试图提供帮助的人!

最佳答案

如果你不提供更多细节,我唯一能做的就是猜测你所看到的行为归结为按钮不如 View “弹性”,因为它们具有由内容决定的“自然”大小(标题和/或图像)和自动布局真的很喜欢强制执行自然大小(正如您从 IB 的警告中看到的那样)。

如果您需要更多帮助,您应该提供更多详细信息。你真的在使用自动布局吗?什么约束?你在做什么动画?等

关于ios - UIView 和 UIButton 的动画区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244633/

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