iosswiftuiviewanimationuianimationanimatewithduration

swift animate all added views alpha


I want to animate all views (based on tag) with an alpha change, but I am getting a "cannot assign alpha to view" error. What would be a good way to do this?

All the views have an alpha of 0 upon being added as a subview of myCustomView

func transitionEffects() {
    UIView.animateWithDuration(0.5, animations: {
        for view in self.myCustomView.subviews {
            if(view.tag != 999) {
                view.alpha = 1
            }
        }
    })
}

Solution

  • This is because Swift needs to know the kind of objects inside the subviews NSArray before sending methods.
    NSArray is automatically converted in a swift Array of AnyType objects, thus it doesn't know which kind of objects are extracted from the array. By casting the array to be an array of UIViews objects everything should work fine.

    func transitionEffects() {
        UIView.animate(withDuration: 0.5, animations: {
            for view in self.myCustomView.subviews as [UIView] {
                if (view.tag != 999) {
                    view.alpha = 1
                }
            }
        })
    }