Teach you to write IOS libraries that can be comfortably and comfortably called and call the ios Library

Source: Internet
Author: User

Teach you to write IOS libraries that can be comfortably and comfortably called and call the ios Library

Directory

Preface

Opening your mind

Analysis

Plastic surgery

Conclusion

 

Preface

 

It was so fast in 2014 and so fast in the new year. In 2015, Nima felt that God was bored and started the acceleration mode by using the variable speed plug-in ~ Up to now, bloggers have been unable to accept the fact that they are already working ...... When the subway face is crowded on the glass, you can only use your eyes to fill the world with silly faces !! Forgive bloggers for chicken manure ~ Because my brother is ill recently, don't worry ~~, I want to think about it. I don't understand how the blogger got sick after four days of fitness every week, his girlfriend pressed his chest muscles, his fist was like a sandpot, his health and health, and he was like a wild horse? I got up one morning and watched the mirror for half an hour before I realized it ~ It was really wrong to look handsome! God is jealous of me ~ Hahaha cough ~ This is a serious technical blog ~ We absolutely reject vulgar content, and the big husband should be right only in the light of the world. Recently, Chai Jing and smog have really touched the hearts of all of us. An extreme organization is like an old one, it's really the treasure Tu's knife in the hand, and the explosive pace of equipment; the recent Hong Kong Island has to catch up with the umbrella ...... I am really worried. Maintaining world peace has always been the wish of the monks. Now the world is so chaotic, I am really ashamed to blame me ~~ There is nothing, so this day, Bo mainly teaches you how to write an IOS library that is easy to use, modifies Ba Shi, and is extremely comfortable for others !!

 

Opening your mind


I am not talented, and it is not a long time to get into the world of code. I have not studied much about the underlying system optimization, framework-level design, and efficiency of design patterns, so if you are a great god and you are a hacker, I suggest you pass by and shut down the webpage ~ I am not afraid of being sprayed with food (I have been sprayed with my teacher for 20 years ...... ^_^) But I have a reverence for the great gods. You can try it if you don't want to let me see you, you don't like the Duang special effects ...... Keke, this article is really a dish ~~~ It is suitable for cainiao who prefer my food.

However, if we want to write a database that can be used by others and can be used comfortably, we must be well-designed, be familiar with the platform, and have a very smooth design model, this is correct ~ However, the platform, architecture, and design are so complicated that I don't understand everyone's explanation. I will not explain it. (If you have to understand the issue of obsessive-compulsive disorder, you can find a university on your own, there is a teacher in it ~)

I swear that we will write an IOS library that can be comfortably and comfortably called together. Recently, toilet paper prices have increased, which is annoying. In fact, there is a reason, because after all, the production cost is also... Who threw the bricks on my head !!?? Believe it or not, I won't beat you ......

Suppose we want to develop something like a circle of friends or Weibo, and we need to be able to hide and expand the body, and identify rich texts (URLs, phone numbers, @ names…) in the body ......) And image thumbnails, click to view, reply, and reply. Rich Text is also supported ...... These functions. Like this
Figure 1


The so-called Gentleman's life is both good and false. Are you sure you are not full? The manager also said that agile development is required. Therefore, code4app and code are flashed. cocoachina sacrifices the strongest killer-search engine, found this library WFCoretext https://github.com/TigerWf/WFCoretext found it perfectly meets our needs, great

 

Analysis


First of all, we would like to thank the author of WFCoretext for his open-source contributions. Please accept my knee and we will use it immediately ~
Figure 2


Few Slots
Let's analyze how it works.
Project Structure 3


Well, the amount is relatively simple. The View folder contains controls.
Figure 4


You can see the specific implementation by yourself. This brother's code style is still relatively standard and does not seem to work hard.
The Manager folder contains rich text matching rules. YMTextData is important.
Let's take a look at how to use
Open WXViewController

Export the package and declare the variable. The variable will be initialized in the subsequent implementation.

# Import "WXViewController. h "# import" YMTableViewCell. h "# import" ContantHead. h "# import" YMShowImageView. h "# import" YMTextData. h "# import" YMReplyInputView. h "# define dataCount 10 # define kLocationToBottom 20 # define kAdmin @" Xiaohu-tiger "@ interface WXViewController () <UITableViewDataSource, metrics, cellDelegate, InputDelegate> {Processing * _ imageDataSource; optional * _ contentDataSource; // NSMutableArray * _ tableDataSource; // tableview data source NSMutableArray * _ shuoshuoDatasSource; // Description: Data Source UITableView * mainTable; UIButton * replyBtn; YMReplyInputView * replyView;} @ end

The three methods initialize a tableview, initialize and assign values to image data, initialize and assign values to other data.

- (void) initTableview;- (void)configImageData;- (void)loadTextData;

 

In loadTextData, the data is packaged into an array of YMTextData, so that the data in a tableCell uses the data of a YMTextData
Then

- (void)calculateHeight:(NSMutableArray *)dataArray

The height of the view occupied by the accounting data in this section also enables the scalability and contraction in our needs.

After the height is calculated, the tableview is reloaded. Then, the various delegate methods of tableview run the datasource methods.

In the following method, we use

 

- (void)calculateHeight:(NSMutableArray *)dataArray

To set the height of tablecell.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {YMTextData *ym = [_tableDataSource objectAtIndex:indexPath.row];BOOL unfold = ym.foldOrNot;return TableHeader + kLocationToBottom + ym.replyHeight + ym.showImageHeight + kDistance + (ym.islessLimit?0:30) + (unfold?ym.shuoshuoHeight:ym.unFoldShuoHeight) + kReplyBtnDistance;}

In the following method, YMTextData is assigned to YMTableViewCell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{static NSString *CellIdentifier = @"ILTableViewCell";YMTableViewCell *cell = (YMTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];if (cell == nil) {cell = [[YMTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];}cell.stamp = indexPath.row;cell.replyBtn.tag = indexPath.row;cell.replyBtn.appendIndexPath = indexPath;[cell.replyBtn addTarget:self action:@selector(replyAction:) forControlEvents:UIControlEventTouchUpInside];cell.delegate = self;[cell setYMViewWith:[_tableDataSource objectAtIndex:indexPath.row]];return cell;}

Arabara ...... Call
I want to ask you if you are tired?
Now I have analyzed this database. Do you know how to use it? Don't doubt your IQ. I have to read it again to know how to use it.
Of course, we cannot doubt the author's contribution to open-source technology! We cannot doubt the author's development technology. After all, this library has few bugs, and the author is great and lofty! This reduces the carbon emissions of the world and facilitates you and me. It provides convenience for many code workers so that they can stay away from working overtime and go home early to accompany their wives and friends with their children and pets ...... So I want to thank the author again.

But as a blogger with perfect obsessive-compulsive disorder, I asked myself why this database is so difficult to use? Because it is difficult to use
How is it easy to use? Which of the following components is easy to use and learn? This should be easy to use.

So next, we need to enable the WXViewController to make DUANG easy to use and comfortable !!

Plastic surgery


We may wish to encapsulate the Implementation Details of WXViewController! It is a tableview, how to calculate the height, how to generate the reply button ...... I don't even care !! My wish is that as long as I throw the data, a circle of friends will be automatically generated !!!!

It's useless to summon X-dragon in a hurry with a desire! The rule is to gather Dragon Ball !!! Let's do it first! Cosmetic WXViewController !!!

We need to develop something called "circle of friends template". In "circle of friends template. h", we need a "circle of friends template Delegate" and there is a method in it.

-(Returned data *) data in the circle of friends in each row: index;

This is what we use:

Real moments. h

@ Interface real circle of friends: circle of friends template <circle of friends template Delegate> @ end

Real circle of friends. m

@ Implementation true circle of friends-(void) viewDidLoad {self. delegate = self;}-(returned data *) data in each row's circle of friends: index {return [array of circle of friends data objectAtIndex: index];} @ end

That's all! You no longer have to worry about how the circle of friends is implemented. You only need to link your data !! Ask if Nice is not Nice ???
So here, as long as you have developed the "circle of friends template. m ", then" friend circle template. h and circle of friends templates. m is the library you have written that can be comfortably invoked and comfortably called! Cool or cool ??

The blogger will teach you how to write this "circle of friends template. m ~~~~

We need to develop a DDRichTextViewController to replace WXViewController <-- this is too difficult to use

Let's write DDRichTextViewController. h first.

 

// Let's get a delegate and datasource ~ In fact, they are all delegate. To improve the registry function, datasource is mainly used to set data related to @ protocol DDRichTextViewDelegate @ required-(NSString *) senderName; // must be implemented! Otherwise, when I comment on others, I hate anonymous scum most. I don't dare to say my name directly !! "Does anyone know that I buy inflatable dolls anonymously? Why is it displayed in text !!! Nana !!" @ Optional-(BOOL) hideReplyButtonForIndex :( NSInteger) index; // whether to hide the reply button. Sometimes we hide the reply button without human reply-(void) didPromulgatorPressForIndex :( NSInteger) index name :( NSString *) name; // the publisher's profile or name is clicked-(void) didRichTextPressedFromText :( NSString *) text index :( NSInteger) index; // callback (void) didRichTextPressedFromText :( NSString *) text index :( NSInteger) index replyIndex :( NSInteger) replyIndex; // callback for clicking the rich text of the comment-(void) replyForI Ndex :( NSInteger) index replyText :( NSString *) text; // callback @ end @ protocol DDRichTextViewDataSource @ required-(YMTextData *) dataForRowAtIndex :( NSInteger) index; // This is the data required for each row! -(NSInteger) rows; // number of rows to be returned @ end @ interface DDRichTextViewController: UIViewController <UITableViewDataSource, UITableViewDelegate, cellDelegate, InputDelegate> @ property (weak, nonatomic) id delegate; @ property (weak, nonatomic) id dataSource; @ end

Then it's DDRichTextViewController. m.
Basically, WXViewController. m is encapsulated! Make the internal implementation details transparent to users
For example, the datasource and delegate of uitableView are implemented in DDRichTextViewController.
In this method, the number of rows to be displayed in tableview is inherited from the datasource of the DDRichTextViewController subclass.

-(NSInteger)numberOfRowsInDDRichText;


The data returned by this method is used as a parameter!

For example:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return [[self dataSource] numberOfRowsInDDRichText];}

So we don't care about this method when using our own database.

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;  

Because we encapsulated

  -(NSInteger)numberOfRowsInDDRichText;

Other implementations and methods are encapsulated.

In this example, @ required is easy to process, and the user must have implemented it, so you can call it directly. However, the @ optional method may not be implemented by the user, so the most important thing is to judge whether the method does not exist: the method is as follows:

RespondsToSelector: NSSelectorFromString (@ "Method Name:") // all classes that inherit NSObject have this method. This is the basis for determining whether the method does not exist at runtime.

The details are as follows:

If ([self. delegate respondsToSelector: NSSelectorFromString (@ "hideReplyButtonForIndex:")]) {// determine whether the hideReplyButtonForIndex method does not exist before executing the following code if ([self delegate] handler: indexPath. section]) {cell. hideReply = YES ;}}

The detailed code is as follows:
(If you want to post detailed code, the blogger will think twice! It is best to download my Demo for research so that you can jump between methods for better understanding !! The address is after the text! And I will love you if you star in the Demo project of the blogger)

Finally, let's take a look at how to use the DDRichTextViewController.

Create a new TestViewController

TestViewController.h#import "DDRichTextViewController.h"@interface TestViewController : DDRichTextViewController<DDRichTextViewDataSource,DDRichTextViewDelegate>@end 

TestViewController. m

/// TestViewController. m // WFCoretext /// Created by David on 15/2/7. // Copyright (c) 2015 tigerwf. all rights reserved. // # import "TestViewController. h "@ interface TestViewController () @ end @ implementation parameters * ymDataArray;-(void) viewDidLoad {[super viewDidLoad]; NSMutableArray MyDataArr = [[NSMutableArray alloc] init]; //!!!! Self should be initialized here. delegate = self; self. dataSource = self;} // The following two methods are datasource method-(NSInteger) numberOfRowsInDDRichText {return 5;}-(YMTextData *) dataForRowAtIndex :( NSInteger) index {return [MyDataArr objectAtIndex: 0]; //! MyDataArr is an array of YMTextData !! Therefore, each item of your circle of friends data must be YMTextData or a subclass that inherits YMTextData !!} // All the methods below are delegate. All the features in the circle of friends use the following delegate method to control the method. optional and mandatory. simple interface call (NSString *) senderName {return @ "David";}-(BOOL) hideReplyButtonForIndex :( NSInteger) index {return NO;}-(void) didPromulgatorNameOrHeadPicPressedForIndex :( NSInteger) index name :( NSString *) name {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "publisher callback" message: [NSString stringWithFormat: @ "name: % @ \ n index: % d", name, index] delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alert show];}-(void) didRichTextPressedFromText :( NSString *) text index :( NSInteger) index {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "" message: [NSString stringWithFormat: @ "content clicked: % @ \ n index: % d ", text, index] delegate: nil cancelButtonTitle: @" OK "otherButtonTitles: nil, nil]; [alert show];}-(void) didRichTextPressedFromText :( NSString *) text index :( NSInteger) index replyIndex :( NSInteger) replyIndex {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "comments of Rich text click callback" message: [NSString stringWithFormat: @ "Click content: % @ \ n index: % d \ n replyIndex: % d", text, index, replyIndex] delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alert show];}-(void) replyForIndex :( NSInteger) index replyText :( NSString *) text {UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "Reply callback" message: [NSString stringWithFormat: @ "Reply content: % @ \ n index: % d", text, index] delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil]; [alert show] ;}@ end

 

The effect is as follows:
Figure 5

Project and Demo address: https://github.com/daiweilai/DDRichText

Conclusion


The author has made many changes to the WXViewController, not just simple encapsulation, but also made regular expressions and names, and made a lot of logical modifications to YMTableViewCell, there are many changes and additions to the callback interface! You need to discover the hidden love of bloggers in person, but in any case this is a sloppy project. It is far from enough to officially use it in enterprise development! No module and unit tests were conducted, and the Image processing method is not good. Here, I directly asked the user to add an Image file. This should be changed to adding an Image address, then let the library asynchronously request for display ...... Therefore, we still need everyone's open-source spirit and power to contribute and burn ourselves. This article is over.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.