Mobile app development for iOS and Swift

Conditionally disable an UIView


This is just a small quick tip on conveniently disabling the interaction on a UIView based on some condition.

Recently I had to implement some kind of access rights mechanism into an app. Within the application it was possible to invite other users with specific access rights - for example restricting the access to some part of the app or some functionality. For that I needed to implement an easy way of disabling any kind of view in the application.

Create an extensions

In order to do so I decided can create an extension on UIView that accepts some type of access right and checks if the current user has the specified access right.

extension UIView {
    func activated(by `do`: AccessRight) {
        if !CurrentUser.isAllowed(to: `do`) {
            alpha = 0.3
            isUserInteractionEnabled = false

The exact implementation of the access rights system in the back is not necessary for this post right now, the only thing which is necessary to know is that there exists a method on the currently logged in user that checks if the user owns the access rights passed to the activated(by:) method. If the user is not allowed to do the specified action, we set the alpha value of the view to 0.3, to visually communicate that the view is currently disabled. Furthermore we set the isUserInteractionEnabled value to false to disable every tap of the user.

With that in place we can call the method in any place to (de)activate user interaction based on some conditions, like access rights:

deleteButton.activated(by: .deleteUser)


And that's it already - with this small extension on the UIView class, we created a simple way of disabling the interaction of a view based on some condition. Furthermore we visualized the disabled state of the view by setting it's alpha value.