Search code examples
swiftcustom-controlsuiactivityindicatorviewaddsubview

How to convert MONActivityView Method for Swift


I'm trying to use a custom ActivityIndicatorView that's written in Obj-C. It contains a method needed to Center the indicator in the UIView frame. I'm having trouble using it in my Swift code. Here is the code...

- (void)placeAtTheCenterWithView:(UIView *)view {
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1.0f
                                                           constant:0.0f]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:view
                                                          attribute:NSLayoutAttributeCenterY
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterY
                                                         multiplier:1.0f
                                                           constant:0.0f]];
}

The link to the GitHub is https://github.com/mownier/MONActivityIndicatorView

How can I use this in Swift?


Solution

  • is this what you looking for ? Convert objective-c to swift ? If that so, here is the translation :

    func placeAtTheCenterWithView(view: UIView) {
        let xCenterConstraint = NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)
        let yCenterConstraint = NSLayoutConstraint(item: view, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
        self.view.addConstraints([xCenterConstraint, yCenterConstraint])
    }
    

    Cheers ;)