【问题标题】:Move text in UITextField with animation使用动画移动 UITextField 中的文本
【发布时间】:2014-01-02 20:51:03
【问题描述】:

我需要将text 移动到UITextField 中(从右到左,然后返回),就像在 iOS 7 中的 Safari 应用程序中 一样(参见下面的屏幕截图)。 有什么办法吗? 我知道我可以设置textAlignment,但不会动画。

也许我应该将leftView 的大小更改为UITextField?但我不确定如何计算大小,什么时候文本应该在中心对齐。请帮忙~


(来源:cs424818.vk.me)

【问题讨论】:

  • 如果我冒昧地猜测一下,我会说它是 UITextField 的一个子类,围绕它构建了很多行为(代码),而这些行为(代码)在常规 UITextField 中是不可用的
  • 这是UITextField和UILabel之间的简单过渡效果(移动+淡入淡出)。这是相当原始的概念。

标签: ios iphone objective-c uitextfield


【解决方案1】:

您可以通过这样做来实现此行为:

- (void)viewDidLoad
{
    // add this to viewDidLoad
    // keep the alignment left justified
    [self.yourTextField setTextAlignment:NSTextAlignmentLeft];
    [self.yourTextField addTarget:self action:@selector(textFieldDidChange)forControlEvents:UIControlEventEditingChanged];
}

-(void)textFieldDidChange
{
    // this will cause your textfield to grow and shrink as text is added or removed
    // note: this will always grow to the right, the lefthand side will stay anchored
    [self.yourTextField sizeToFit];
}

然后,当您想将 UITextField 从中心移到左侧时,您只需执行以下操作:

// 1 second animation
[UIView animateWithDuration:1.0 animations:^{
    // move to the left side of some containing view
    self.yourTextField.center = CGPointMake(containingView.frame.origin.x + self.yourTextField.frame.size.width/2, self.yourTextField.center.y);
}];

同样从左侧移动到中心你可以这样做:

[UIView animateWithDuration:1.0 animations:^{
    // move to the center of containing view
    self.yourTextField.center = CGPointMake(containingView.frame.size.width/2, self.yourTextField.center.y);
}];

希望这会有所帮助!

【讨论】:

  • 我很想将 viewDidLoad 和 textFieldDidChange(例如 [self.yourTextField sizeToFit])放在 self.yourTextField 而不是 your_textfield。如果我错了,请纠正我:)
  • 感谢您的回答!但我有一个问题:当UITextField 中的文本宽度大于视图大小时,怎么办?所以如果我使用sizeToFit,UITextfield 就会超出视图。 @MikeSlutsky
  • 你应该尝试使用这个:Growing Text View
  • 但是为什么呢?我没有看到任何文本从中心移动到另一侧/从另一侧移动到中心。 @nlee918
  • 对不起,我不确定我明白你的意思。您是否希望 UITextField 为特定宽度,并允许文本溢出? (sizeToFit 确实完全使 textField 更大以适合所有文本)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
相关资源
最近更新 更多