teach you to write iOS libraries that are comfortable and comfortable to call

Source: Internet
Author: User

Directory

Objective

The brain opens.

Analysis

Cosmetic

Conclusion

Preface

2014 is so fast, the new year is so block, 2015 is a fast rhythm, really funny feeling God is not bored with the use of variable speed plug-in opened the accelerated mode ~ Now bloggers are unable to accept the fact that they have to work ... When the subway face is squeezed in the glass, you can only use eyes to write a silly X-ray of the world face!! Forgive Bo master so chicken Dung ~ because elder brother recently ill, not hi Heart ~ ~, I want to think not understand, Bo Master fitness 4 days a week, chest muscle pressure girlfriend, fist than sand pot, eat and drink health and health, body hard like Mustang, how can be sick? I puzzled for a few days, and finally one day in the morning to see the mirror half an hour later I only Epiphany, I am the original look handsome really is wrong! God is jealous of me to make me sick ~ hahaha cough ~ This is a serious technical blog ~ is absolutely refused to esu low content, man should be the heart of the world is right, the recent Chai Jing and haze really touched our hearts; an extremist organization like hey big, really is the Dragon Slayer Blades in hand, equipped with the rhythm of the explosion , near the island of Hong Kong to finish the umbrella again to rush people ... I am really very bitter, the maintenance of world peace has been my wish, the world is so chaotic, I am really ashamed, all blame me ~ ~ Not because of what, so today Bo mainly teach you how to write a self with ease, modify Barth, others use up and extremely comfortable iOS library!!

The brain opens .


I am not, contact code of the world time really is not very long, for the system bottom optimization, frame level design, design model efficiency and so on the study and research is not profound, so if you are the big God, you ruthless slip words, I still suggest you pass hehe and then close this webpage, tricks can't come to see AH ~ I am not afraid of being sprayed very much (after all, it has been sprayed by the teacher for 20 years ... ^_^) but I have a fear of the great God, can not say that you see it, you may try it, you do not like to read after the Duang so many special effects ... Cough anyway this article really very dish ~ ~ ~ is suitable than my vegetable's rookie, cautiously reads.

However, we have to write a library, can let others use, to be very comfortable, that must be designed properly, must be familiar with the platform, design patterns are very slip, this is right ~ but the platform, architecture, design this thing so complex, I explain that we do not understand, Then I will not explain (your obsessive-compulsive attack to die to understand can find a university, there are teachers ~)

I swear I'm not talking about BB. Let's write an iOS library that can be comfortable and comfortable to call, the recent price of toilet paper, good annoying, in fact, there is a reason, because after all, production costs and so on ... Who threw the bricks on my head!? Believe it or not, I won't kill you.

Let's say we're going to develop something like a circle of friends or Twitter, and have the ability to hide and expand the text, the body can identify rich texts (URL, phone, @ name ...). ), and to have picture thumbnails and click to view, can reply, reply to the text also support rich text ... These features. Like this
Figure 1


The so-called gentleman born non-different also good false in things also. The above features so much so complicated to write yourself, are you sure you're not fed up? The manager also said to be agile development, so apart flashed to Code4app,code.cocoachina sacrificed the strongest kill device-search engine, found the library Wfcoretext Https://github.com/TigerWf/WFCoretext Find it perfectly fit our needs yes, great

Analysis


First of all, we thank the author of Wfcoretext's Open source contribution, please accept my knees, we immediately come with a use ~
Figure 2


Not many slots.
Let's analyze it.
Engineering Structure Diagram 3


Yes, well, it's a simple view folder, it's a control.
Figure 4


Concrete implementation you can see for yourself, the elder brother code style is still relatively standard, it does not seem laborious
There are some rich text matching rules in the Manager folder, where Ymtextdata is important.
Let's take a look directly at how to use the
Open Wxviewcontroller.

Guides and declares variables, which are initialized in the implementation of the next 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 @"小虎-tiger"@interface WXViewController ()<UITableViewDataSource,UITableViewDelegate,cellDelegate,InputDelegate>{NSMutableArray *_imageDataSource;NSMutableArray *_contentDataSource;//模拟接口给的数据NSMutableArray *_tableDataSource;//tableview数据源NSMutableArray *_shuoshuoDatasSource;//说说数据源UITableView *mainTable;UIButton *replyBtn;YMReplyInputView *replyView ;}@end

These three methods are constructed to initialize a TableView, initialize and assign a value to the image data, initialize and assign other data

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

In Loadtextdata, the data is wrapped into an array of ymtextdata, so that the data inside a TableCell uses a ymtextdata of data
And then in

- (void)calculateHeight:(NSMutableArray *)dataArray

It calculates the height of the view occupied by the data. It also allows us to expand the function that can be shrunk in our needs.

Calculate the height and then reload the TableView and then tableview the various delegate methods of the various datasource methods on the Whistling run

One of the following methods is again used in our

- (void)calculateHeight:(NSMutableArray *)dataArray

The height calculated in the method to set the height of the 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;}

The following method assigns the Ymtextdata to the 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;}  

Alabara ... Whirring
I just want to ask you a tired?
Now I have analyzed this library, you know how to use it, do not doubt their IQ, I have to look again to know how to use.
Of course, we can't doubt the author's contribution to open source technology! We also can not doubt the author of the development of technology, after all, the library bug is still relatively small, the author is great and lofty! Reduce the carbon emissions of the world convenient for you I he, for a lot of code workers to provide convenient, so that they can not work overtime, early home with the wife accompany the friends with the children with the pet ... So I want to thank the author again

But as a blogger with a perfect obsessive-compulsive disorder, ask yourself why this library is so hard to use? Because it's hard to use
How can it be useful? System comes with components that are easy to use and learn? This should be useful.

So next, we want to operate Wxviewcontroller let him duang, become comfortable comfortable and comfortable!!

Cosmetic Surgery


We may as well wxviewcontroller the implementation details to wrap up! It is a tableview, how it calculates the height, how its reply button is generated ... Balabala I don't want to care!! My wish is, I just throw in the data, automatically generate a circle of friends!!!!

With a wish, the rush to summon the dragon is useless! The rule is to collect Dragon Beads!!! Okay, let's do it first! Cosmetic wxviewcontroller!!!

We're going to develop something called a "circle of friends template." In the "friend Circle template. h" There is a "friend Circle template Delegate" and there's a way inside.

-(returned data *) data for each line of the friend Circle: index;

This is how we use it:

True friend Circle. h

@interface 真朋友圈 : 朋友圈模板<朋友圈模板Delegate> @end

True friend Circle. M

@implementation 真朋友圈- (void)viewDidLoad {self.delegate = self;}-(返回的数据*)每行朋友圈的数据:index{return [朋友圈数据数组 objectAtIndex:index];}@end

That's good! You don't have to worry about how the circle of friends is going to come true. You just have to relate your data section!! Just ask you nice???
So as long as you have developed "friend Circle template. M" then "friend Circle template." H "and" friend Circle template. M "is the library you've written that can be comfortable and comfortable to call! Cool not cool??

The blogger will teach you how to write this "circle of friends template." M "Ah Hee Xi-ho hands-on Oh hands yo bo master is very love Oh ~ ~ ~ ~

We're going to develop a ddrichtextviewcontroller to replace Wxviewcontroller <--, which is too hard to use.

Let's write DDRichTextViewController.h first.

Learn about system components and we're going to get a delegate and datasource~ are actually delegate. In order to better differentiate functionality, DataSource is primarily used to set data about @protocol Ddrichtextviewdelegate @ required-(nsstring*) sendername;//must be realized! Otherwise comment on others when no name most hate anonymous slag, their name is not dare to say directly!! "Who knows that I buy inflatable dolls are anonymous Ah, huh?" Why my mind will become a text to show out!!! Nani!! "@optional-(BOOL) Hidereplybuttonforindex: (Nsinteger) index;//whether to hide the reply button, sometimes we do not let people reply to hide the reply button-(void) Didpromulgatorpressforindex: (nsinteger) index name: (nsstring*) name;//the publisher's avatar or name is clicked-(void) Didrichtextpressedfromtext: (nsstring*) text index: (nsinteger) index;//text-rich-clicked callback-(void) Didrichtextpressedfromtext: (nsstring*) text index: (nsinteger) Index Replyindex: (Nsinteger) replyindex;// Comment Rich Text clicked Callback-(void) Replyforindex: (nsinteger) Index Replytext: (nsstring*) text;//reply to the contents of the text callback @end@protocol Ddrichtextviewdatasource @required-(ymtextdata*) Dataforrowatindex: (Nsinteger) index;//This is the data needed for each line! -(Nsinteger) numberofrowsinddrichtext;//How many rows need to be returned @end@interface ddrichtextviewcontroller:uiviewcontroller< Uitableviewdatasource,uitableviewdelegate,celldelegate,inputdelegate> @property (weak, nonatomic) ID delegate; @property (weak, nonatomic) ID dataSource; @end 

And then it's ddrichtextviewcontroller.m.
It's basically a package for WXVIEWCONTROLLER.M! Make the details of its internal implementation transparent to the user
In Ddrichtextviewcontroller, for example, UITableView DataSource and delegate are realized.
In this method tableview the number of rows that need to be displayed is from the datasource of the subclass that inherits the Ddrichtextviewcontroller

-(NSInteger)numberOfRowsInDDRichText;


This method returns the data as a parameter!

such as this:

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

So when we use our own library, we don't really care about this method.

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

Because we're encapsulated in the

  -(NSInteger)numberOfRowsInDDRichText;

Similar to other implementations and methods are encapsulated

This process @required is very simple, the user must have already implemented, so the direct call is good. But @optional method users do not necessarily want to implement, so the most important thing is to determine that this method does not exist: The method is as follows

Respondstoselector:nsselectorfromstring (@ "method Name:")//The class that inherits NSObject has this method this is the foundation, is the runtime judgment method existence does not exist

Details are as follows

if ([self.delegate respondsToSelector:NSSelectorFromString(@"hideReplyButtonForIndex:")]) { //判断hideReplyButtonForIndex方法存不存在 存在才会执行如下的代码if ([[self delegate] hideReplyButtonForIndex:indexPath.section]) {cell.hideReply = YES;}}

Here is the detailed code
(originally wanted to post detailed code, Bo master a thought!) It is best to download my demo for research so that you can jump between the methods to see more understand!! The address is behind the text! And you're in the blogger's demo project, Star, I love your Y.

Finally, let's see how to use the written ddrichtextviewcontroller.

We're building 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 Testviewcontrollernsmutablearray * ymdataarray;-(void) viewdidload {[Super viewdidload]; Nsmutablearray Mydataarr = [[Nsmutablearray alloc]init];//!!!! This should initialize the data yourself self.delegate = Self;self.datasource = self;} The following two are DataSource methods-(Nsinteger) Numberofrowsinddrichtext{return 5;} -(Ymtextdata *) Dataforrowatindex: (Nsinteger) Index{return [Mydataarr objectatindex:0];//!!!!!!!! Mydataarr is an array of Ymtextdata!! So your circle of friends every item of data must be a subclass of Ymtextdata or inheriting Ymtextdata!! }//all of the following are delegate's methods. All features of the circle of friends use the following delegate method to control the method with optional and required to implement the interface call is simple-(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:@ "Text Rich Text Click callback" Message:[nsstring stringwithformat:@ "clicked content:%@\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:@ "Comment Rich Text click callback" Message:[nsstring stringwithformat:@ "clicked content:%@\n index:%d \ 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 to 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


Bo Master of Wxviewcontroller Change is still a lot of, not only is simple encapsulation, I also made the expression and name of the regular judgment, but also to Ymtableviewcell made a large number of logical changes, callback interface to make changes and add a lot! Need you to find the blogger's hidden love, but in any case this is a sloppy project, want to formally use in enterprise development this is not enough! No module and unit testing, where the image processing is not good, here I directly ask the user to add image file this should be changed to add image address, and then let the library asynchronous to request the display ... So still need everyone's open source spirit and strength to contribute their own, burning their own, the article ended the Sao

teach you to write iOS libraries that are comfortable and comfortable to call

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.