Creating subclass of UIImageView

2019-05-26 12:42发布

问题:

I havent found the option of UIImageView to choose from dropdown during creating objective-c class. I am using xcode 4.3. I want to know arent we allowed to extend UIImageView class. Or do i have to inherit UIView ? Any sample structure of custom UIImageView class would be helpful.

Thanks

回答1:

I believe it's considered bad practice to subclass UIImageView. If you take a look at this question, there are many examples of why you shouldn't do it:

  • A part of the Gang of Fours design pattern philosophy is to "Favor 'object composition' over 'class inheritance'." This reduces the tight coupling between ojects. Then changing one class will have less impact on the other classes in the system. This makes changes easier, resulting in a more stable, easy to maintain system.

  • The reason it is subclassing UIView is so that you should, for example, display a UIActivityIndicator while the image is being downloaded. They do not show this in their example but I have used this code and it is really good. Also look at the comments for this post you will find more code examples, also including some caching and nice stuff.

However, it is possible to subclass UIImageView. Just take a look at this question.

A good alternative, suggested in the aforementioned question, is to use a category instead of subclassing UIImageView:

  • I would suggest using an Objective-C "Category" instead of subclassing the UIImageView. As long as you don't have to add any member variables, a Category is a better solution. When you use a category you can call your extended functions on any instance of the original class (in your case UIImageView. That removes the need for you to consciously use your subclass anywhere you might want to use your new functions.

Hope this helps!



回答2:

You can subclass UIImageView. Even though qegal's answer contains a lot of right stuff you should keep in mind, just put the cursor into the drop down and start typing the name of any class you want to inherit and it will start auto completion.