Reputation: 3623
I have a class that defines all styles on a UIVIew. They are all predefined but I'm not sure when to fire this.
When I try to create an extension for this:
extension UIView
{
func willMoveToSuperview(newSuperview: UIView?)
{
self.stylize() // Another extension somewhere (not here my problem)
}
}
And I'm getting this error:
Method 'willMoveToSuperview' with Objective-C selector conflicts with previews declaration with the same Objective-c selector
I have tried to override it, but didn't worked either.
Any ideas on how to be able to apply a same behaviour when all of my UIViews will become visible?
Upvotes: 2
Views: 1388
Reputation: 13689
Outside of swizzling (not generally recommended), or subclassing as noted by David in his answer, there isn't really a way to override existing methods on a class and its subclasses.
One thing you might try is creating a base class for your view controller instead of all your views. In your view controller base class, you could override viewWillLayoutSubviews
to recurse through the view hierarchy and call stylize
on each view. This means you would be using the subclass approach in fewer places (just view controllers as opposed to all views).
Another thing you might consider if taking the subclassing approach with UIView is that if you are subclassing anyway, you can take advantage of things like @IBDesignable and @IBInspectable to better integrate those UIView subclasses with storyboards and live preview.
I wrote a Swift library which does exactly this, and it works well for the type of styling it seems you want to do: https://github.com/daniel-hall/Stylish
Upvotes: 0
Reputation: 15804
You can use Swizzling technic to customize UIView's function. Take a look at:
or
Hope that helps.
Upvotes: 1
Reputation: 6112
You can create a subclass of UIView
with the method .stylize()
.
Then each view you create, you inherit of you UIView
subclass.
You'll be able to cal .stylize()
on each UIViewSubclass. Simply write the style code inside the subclass and inherite.
Or
Use a category to add the method to the existing UIView
class.
Upvotes: 0
Reputation: 2540
Even though Swift's Extensions
are similar to Categories
from Objective-C, what you are trying to do is not allowed in Swift.
You cannot override
existing functionality:
Extensions can add new functionality to a type, but they cannot override existing functionality.
Source: Swift Extensions - Apple Documentation
Depending on what it is that you are trying to style, you might want to take a look at UIAppearance
, it will allow you to style default colors for the UINavigationBar
, amongst other things. NSHipster has a good post about it: NSHipster - UIAppearance
Upvotes: 0