将Obj-C转换为Swift问题(即:NSDictionaryOfVariableBindings)

时间:2015-03-25 06:10:10

标签: swift

我在Objective-C中将@ Rob' s answer转换为Swift时遇到了一些问题:

例如,我不确定一些事情,例如:NSDictionaryOfVariableBindings in swift

目标C

- (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 Attempt

@IBOutlet var button1: UIButton!

func addUnderline() {
    var underlineView: UIView = UIView()
    underlineView.setTranslatesAutoresizingMaskIntoConstraints(false)
    underlineView.backgroundColor = UIColor.lightGrayColor()
    self.view.addSubview(underlineView)
    //self.underlineView = underlineView;

    updateConstraintsForUnderlineView(underlineView, underButton: self.button1)
}

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

func updateConstraintsForUnderlineView(underlineView: UIView, underButton: UIButton) {
if self.underlineConstraints {
    self.view.removeConstraints(self.underlineConstraints)
}

    let views: NSDictionary = ["underlineView":underlineView, "button": button1]
    self.underlineConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[button]-[underlineView(5)]", options: NSLayoutFormatAlignAllLeading, metrics: nil, views: views)
    self.view.addConstraints(self.underlineConstraints)
}

0 个答案:

没有答案