我的情节提要板上有一个按钮。此按钮在视图内部,而该视图在滚动视图内部。
我尝试做的事情听起来很简单:按下按钮时,按钮向下移动了一点,并且出现了textField,该位置以前是按钮所在的位置。
但是,发生的情况是按钮设置了动画,然后返回到其原始位置,而不是保持移动,并且textField出现了应有的状态。
因为出现的textField的位置取决于按钮的位置,所以多次按下按钮只是简单地将一堆文本字段放在彼此的顶部。
这是发生的情况的图片:
my Screen:
这是按下按钮时我正在运行的代码:
@IBAction func addIngredientButtonPressed(发送者: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的高度),则您得到的行为几乎正确。按钮移动并保持移动,textField出现在正确的位置,但是如果您持续按下,则不允许添加的textField超出屏幕大小。
这是如果注释掉前两行会发生什么情况的图片。如果您继续按下该按钮,将无法执行任何其他操作:
screen filled:
我找到了很多教程,它们告诉您如何使用情节提要和如何将推断的指标设置为自由格式来添加超出一个屏幕的内容,但是我还没有发现有人尝试像我一样动态地添加元素。
最佳答案
您似乎有一个contentView
-大概是scrollView
的直接子视图,但是您是将newIngredientTextField
直接添加到scrollView
而不是contentView
中。
增大bounds.size.height
的contentView
时,它会将其frame.origin.y
减小一半(以将其center
保留在同一位置)。由于您的原始按钮可能是该contentView
的子视图,因此它将独立于新添加的文本字段移动。
换句话说,写:contentView.frame.size.height += addIngredientLabel.bounds.height
而不是contentView.bounds.size.height += addIngredientLabel.bounds.height
和contentView.addSubview(newIngredientTextField)
而不是scrollView.addSubview(newIngredientTextField)
。
关于swift - 如何以编程方式将textField添加到滚动 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34885427/