gpt4 book ai didi

ios - 以编程方式快速定义 UIButton

转载 作者:行者123 更新时间:2023-11-28 06:20:38 25 4
gpt4 key购买 nike

我正尝试按如下方式以编程方式添加按钮。

    lazy var myButton: UIButton = {
let button = UIButton(type: .System)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.blueColor()
button.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2)
button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
return button
}()

我的意图是创建一个按钮,其宽度和高度为 View 高度的一半。而且我还对这个按钮设置了 LeftAnchor、RightAnchor、WidthAnchor、TopAnchor 约束。

我的 viewDidLoad()

中有以下代码
view.addSubview(myButton)

当我尝试运行这段代码时,我无法准确地看到我想在我的模拟器上拥有什么。我希望看到 button width = view' width and height of button = view height/2

相反,我在模拟器的左上角看到了一个小按钮。我该如何解决这个问题?

谢谢!

最佳答案

更好的选择是使用 AutoLayoutConstraints。

var myButtonHeight: NSLayoutConstraint

view.addSubview(myButton)
myButton.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
myButtonHeight = myButton.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)
myButtonHeight.isActive = true

如果按钮高度的更改是 onTouchDown,如果它是 onTouchUpInside 的结果,则您的评论不清楚,但无论哪种方式

myButtonHeight.constant = (buttonShouldBeTall) ? 20 : 0
view.setNeedsLayout()

请记住,您还需要定位 leading/trailing/centerX anchor 和 leading/trailing/centerY anchor ,具体取决于您需要的位置

关于ios - 以编程方式快速定义 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43642229/

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