gpt4 book ai didi

swift - 如何以编程方式将文本字段添加到 ScrollView

转载 作者:行者123 更新时间:2023-11-30 13:46:19 25 4
gpt4 key购买 nike

我的 Storyboard上有一个按钮。该按钮位于 View 内,而该 View 位于 ScrollView 内。

我想做的事情听起来相对简单:按下按钮时,按钮会向下移动一点,并且文本字段会出现在按钮之前所在的位置。

但是,发生的情况是按钮动画,但随后返回到其原始位置,而不是保持移动,并且文本字段按其应有的方式显示。

由于出现的文本字段的位置取决于按钮的位置,因此多次按下按钮只会将一堆文本字段放在彼此的顶部。

这是发生的情况的图片:

my Screen:

这是按下按钮时我运行的代码:

@IBAction func addIngredientButtonPressed(sender: UIButton) {

contentView.bounds.size.height += addIngredientLabel.bounds.height

scrollView.contentSize.height += addIngredientLabel.bounds.height


//Create Text Field and Set Initial Properties
let newIngredientTextField = UITextField(frame: CGRectMake(self.addIngredientLabel.frame.minX as CGFloat, self.addIngredientLabel.frame.midY as CGFloat, self.addIngredientLabel.bounds.width,self.addIngredientLabel.bounds.height * 0.60))

newIngredientTextField.font = UIFont.systemFontOfSize(15.0)
newIngredientTextField.placeholder = "ADD INGREDIENT HERE"
newIngredientTextField.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left

newIngredientTextField.alpha = 0.0

scrollView.addSubview(newIngredientTextField)



UIView.animateWithDuration(0.5) { () -> Void in

self.addIngredientLabel.center.y += self.addIngredientLabel.bounds.height
newIngredientTextField.alpha = 1.0

}

}

注意:** 长度也已成功添加到屏幕,但按钮没有保持移动状态。因此,在上面的屏幕截图中,您确实可以上下滚动 **

我注意到,如果您注释掉前两行代码,即为 contentView 和scrollView 添加高度的代码,您将获得几乎正确的行为。按钮移动并保持移动,文本字段出现在正确的位置,但如果您继续按下,它不会让您添加超出屏幕尺寸所能容纳的文本字段。

下面的图片显示了如果注释掉前两行会发生什么情况。如果您继续按下去,该按钮将不会执行任何操作:

screen filled:

我发现很多教程告诉您如何使用 Storyboard 添加比一个屏幕所能容纳的内容更多的内容,并将推断的指标设置为自由形式,但我还没有发现有人像我一样尝试动态添加元素。

最佳答案

您似乎有一个 contentView - 可能是 scrollView 的直接 subview ,但您将 newIngredientTextField 直接添加到您的scrollView 而不是您的 contentView

当您增加 contentViewbounds.size.height 时,它的 frame.origin.y 会减少一半(将其中心保持在同一位置)。由于您的原始按钮可能是此 contentView 的 subview ,这将导致它独立于新添加的文本字段移动。

换句话说,写:

contentView.frame.size.height += addIngredientLabel.bounds.height

而不是

contentView.bounds.size.height += addIngredientLabel.bounds.height

contentView.addSubview(newIngredientTextField)

而不是

scrollView.addSubview(newIngredientTextField)

关于swift - 如何以编程方式将文本字段添加到 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34885427/

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