将一个按钮下的动画线转换为另一个按钮

时间:2015-02-26 17:02:57

标签: swift

在Swift中,我试图复制此应用程序的动画下划线。当用户点击" local"或者" world",下划线栏在屏幕上滑动并位于所选按钮下方。

动画是如何完成的?条形图是移动的图像视图吗?

enter image description here

1 个答案:

答案 0 :(得分:5)

你问:

  

动画是如何完成的?条形图是移动的图像视图吗?

很可能它只是一个UIView,其背景颜色是浅蓝色,其帧(或定义帧的约束)在[UIView animateWithDuration:]块内更改。


例如,在Objective-C中,您可能具有以下属性:

@property (nonatomic, weak) UIView *underlineView;
@property (nonatomic, strong) NSArray *underlineConstraints;
@property (nonatomic, weak) IBOutlet UIButton *button1; 

和这段代码:

- (void)addUnderline {
    UIView *underlineView = [[UIView alloc] init];
    underlineView.translatesAutoresizingMaskIntoConstraints = NO;
    underlineView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:underlineView];
    self.underlineView = underlineView;

    [self updateConstraintsForUnderlineView:underlineView underButton:self.button1];
}

- (IBAction)didTapButton:(UIButton *)sender {
    [self updateConstraintsForUnderlineView:self.underlineView underButton:sender];
    [UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)updateConstraintsForUnderlineView:(UIView *)underlineView underButton:(UIButton *)button {
    if (self.underlineConstraints) {
        [self.view removeConstraints:self.underlineConstraints];
    }

    NSDictionary *views = NSDictionaryOfVariableBindings(underlineView, button);
    self.underlineConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[button]-[underlineView(5)]" options:NSLayoutFormatAlignAllLeading | NSLayoutFormatAlignAllTrailing metrics:nil views:views];
    [self.view addConstraints:self.underlineConstraints];
}

或者在Swift中:

weak var underlineView: UIView!
var underlineConstraints: [AnyObject]!
@IBOutlet weak var button1: UIButton!

func addUnderline() {
    let underlineView = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    underlineView.backgroundColor = UIColor.lightGrayColor()
    view.addSubview(underlineView)
    self.underlineView = underlineView

    updateConstraintsForUnderlineView(underlineView, underButton:button1)
}

@IBAction func didTapButton(sender: UIButton) {
    updateConstraintsForUnderlineView(underlineView, underButton:sender)
    UIView.animateWithDuration(0.25, delay: 0.0, options: .CurveEaseOut, animations: { () -> Void in
        self.view.layoutIfNeeded()
    }, completion: nil)
}

func updateConstraintsForUnderlineView(underlineView: UIView, underButton button: UIButton) {
    if underlineConstraints != nil {
        view.removeConstraints(underlineConstraints)
    }

    let views = ["underlineView": underlineView, "button": button]
    underlineConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[button]-[underlineView(5)]", options: .AlignAllLeading | .AlignAllTrailing, metrics: nil, views: views)
    view.addConstraints(underlineConstraints)
}