The difference between TableView and ScrollView in iOS

Source: Internet
Author: User

ScrollView:

1. Introduction ScrollView Some properties

1>: To use ScrollView you have to do two things.

1). Set ScrollView Content

2). Set Contentsize (scroll range)

2> other properties

1). Contentoffset (scroll position)

2). Contentinset (additional scrolling area added)

3). Bounces (set Uiscrollview if spring effect is required)

4). crollenabled (Sets whether Uiscrollview can scroll)

5). Showshorizontalscrollindicator (whether the horizontal scroll bar is displayed)

6). Showsverticalscrollindicator (whether vertical scroll bar is displayed)

2. Agent

Two thoughts of 1> agent thought

1). Listening idea: B listen to a what's going on

2). Notice the idea: a something has happened, to inform B to do

2>scrollview's proxy usage

1). How to become an agent (three steps)

* Declaration protocol * Set proxy object self.scrollView.delegate = self; * Implement Protocol method

2). Agent monitoring ScrollView drag and drop events

Start dragging-(void) scrollviewwillbegindragging: (Uiscrollview *) ScrollView;             End drag-(void) scrollviewdidenddragging: (Uiscrollview *) ScrollView willdecelerate: (BOOL) decelerate; ScrollView when scrolling-(void) Scrollviewdidscroll: (Uiscrollview *) ScrollView

3). Scaling with Agents

* Become a Uiscrollview agent () * Set Scaling object (by Viewforzoominginscrollview method) * Set Zoom to Range (Maximumzoomscale, Minimumzoomscale)

3. Timer creation Two ways

1>. Self.timer = [Nstimer scheduledtimerwithtimeinterval:1.f target:self Selector: @selector (method) Userinfo:nil Repeats:yes]   ; When another scrollview is running, the timer's ScrollView is stopped and only one scrollview is executed.

2>.   Self.timer = [Nstimer timerwithtimeinterval:1.f target:self Selector: @selector (method) Userinfo:nil Repeats:yes]; [[Nsrunloop Mainrunloop] AddTimer:self.timer formode:nsrunloopcommonmodes];

4. Customize the protocol and use

1> Define protocol (three steps)

* Define protocol (two kinds of optional[proxy objects do not implement], required[proxy objects must be implemented])

* Increase agent properties (weak) @property (weak, nonatomic) id<lfappinfoviewdelegate> delegate;

* Send a message to the agent, call the proxy method (you need to determine whether the proxy object implements the method, do not judge the call (not compile) will error) Note: Define the name of the protocol [class name +delegate], protocol method naming specification [method name need to remove the prefix, and self as a parameter]

2> Using a proxy (three steps)

* Declaration Agreement

* Set proxy Object

* Implement protocol method (this example is to add a Uilabel to the proxy object [controller])

TableView:

1. UITableView need to set up a data source to display data

1>. How many groups are queried to the data source, how many rows per group, what data is displayed for each row

2> The data source must comply with the Uitableviewdatesource protocol

3> How many groups are there altogether?

-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{} section group how many rows

-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) section{} What is displayed in each row

-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{} What title does the section group head Show-(NSString *) TableView: (UITableView *) TableView titleforheaderinsection: (nsinteger) se ction{} What title is displayed at the bottom of section group

-(NSString *) TableView: (UITableView *) TableView titleforfooterinsection: (Nsinteger) section{} Use the proxy method to set the cell height when the cell height of each row is inconsistent

-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{} Use the property to set the cell height when the cell height of each row is consistent

Self.tableView.rowHeight = 60; Variable array definitions that can optimize memory

Nsmutablearray *models = [Nsmutablearray arraywithcapacity: (Nsuinteger)]

2. Cell Common Properties

1>.cell.textlabel.text Title

2>.cell.detailtextlabel.text Introduction

3>.cell.imageview.image Pictures

4>.cell.accessoryview Auxiliary View

5>.cell.accessoryview Customizing auxiliary views

6>.cell.backgroundview Setting the cell background color

1). You can set the cell background via backgroundcolor and Backgroundview

2). But Backgroundview has a higher priority than backgroundcolor.

3). So if BackgroundColor and Backgroundview are set at the same time, Backgroundview will cover the backgroundcolor

7>.cell.selectedbackgroundview setting the background of the selected state

3. UITableView Common Properties

1>. Tableview.separatorstyle Setting the split line style

2>. Tableview.separatorcolor set the split line color custom color

[Uicolor colorwithred: Color value/255.f Green: Color value/255.F Blue: color value/255.f Alpha: color value/255.f];

Get screen width: [UIScreen mainscreen].bounds.size.width;

3>. Tableview.tableheaderview Set TableView head view is typically used for advertising

4>. Tableview.tablefooterview Setting the bottom view of TableView is typically used to place load more buttons

5>. [Self.tableview Reloaddata]; Refresh table//Refresh specified row

Nsindexpath *path = [Nsindexpath indexpathforrow:row insection:0]; [Self.tableview Reloadrowsatindexpaths:@[path] withrowanimation:uitableviewrowanimationright];

4. Ways to optimize cells

1>: First go to the cache pool to find if there is a cell uitableviewcell *cell = [TableView dequeuereusablecellwithidentifier:identifier] that satisfies the condition;

2> If there is no qualifying cell in the cache pool, create a cell if (nil = = cell) {cell = [[UITableViewCell alloc] Initwithstyle:uitableview     Cellstylesubtitle Reuseidentifier:identifier]; }

3> Create a cell and set a unique tag: identifier Note: Defining a variable NSString *identifier recommends static local variables defined with static, and macros are not recommended.

4>: Set the cell data and return the cell

5. TableView Proxy method

1>. -(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) indexpath{}//Called when a row is selected

2>. -(void) TableView: (UITableView *) TableView Diddeselectrowatindexpath: (Nsindexpath *) indexpath{}//Called when a row is unchecked

3>. Some properties and proxy methods of Uialertview

1). Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Modify data" Message:nil delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil]; Create a pop-up window

2). Alert.alertviewstyle = Uialertviewstyle ...; Set the alert style so that alert displays the Uitextfield

3). Uitextfield *textfield = [alert textfieldatindex:0]; Get the TextField in alert

4). [Alert show]; Show pop-up window

5).-(void) Alertview: (Uialertview *) Alertview Clickedbuttonatindex: (Nsinteger) buttonindex{}// The Alertview button is called when it is clicked.

6. Custom cell Two ways

1>. Pure code: The number and location of each cell child control is different

2>. The way to load xib with the same fixed interface as Xib:cell:

1). [[[NSBundle Mainbundle] loadnibnamed:@ "xib name" Owner:nil Options:nil] firstobject];

2).         uinib *nib = [uinib nibwithnibname:@ "xib name" Bundle:nil];   UIView *view = [[nib Instantiatewithowner:nil options:nil]firstobject]; 3>. Deferred call Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (3.0 * nsec_per_sec)), Dispatch_get_main_queue ()   , ^{   }); The 4>.init method is called only when the control is created through code; The Awakefromnib method is called when the control is created by Xib or storyboard.

5>. Protocol specification protocol Name: Control name + Delegate protocol method name: control name minus prefix + meaning in the protocol method, the purpose of sending yourself (triggering a release) control out is to make it easier to distinguish which control triggered the method

6>. Code-created child controls, added to Contentview [self.contentview addsubview: child controls];

7>. Calculate text width high cgsize *maxsize = Cgsizemake (maxfloat); Set text range nsdictionary *dict = @{nsfontattributename:font}; Font//If future computed text ranges beyond the specified range, returns the specified range//If the future computed text is less than the specified range, the true range is returned cgsize siz e = [NSString *str boundingrectwithsize:maxsize options:nsstringdrawinguseslinefragmentorigin attributes:dict Context : Nil].size; Calculate Text Width Height

8> methods for customizing cells by code

1). Create a new class that inherits from UITableViewCell

2). Override the Initwithstyle:reuseidentifier: method to add all the child controls that need to be displayed (you do not need to set the child controls to the data and frame, and the child controls to add to the Contentview). property settings (some properties only need to be set once, such as fonts \ fixed images)

3). Provides 2 model data models: storing text data \ Picture Data frame model: The height of the Frame\cell that holds the data model \ All child controls 4). The cell has a Frame model (do not have a data model directly)

5). Override the setter method of the Frame model property: Set the child control's display data and frame in this method

6). The initialization of the frame model data has been lazy-loaded (each cell corresponds to the frame model data is loaded only once)

7. Notification mechanism

1>. Notification hubs (Nsnotificationcenter) Each application has a notification hubs (Nsnotificationcenter) instance that is specifically responsible for assisting message communication between different objects to create a notification hub NS Notificationcenter *center = [Nsnotificationcenter defaultcenter];

2>. A complete notification typically contains 3 attributes:-(NSString *) name; Name of the notification-(ID) object; Notifies the publisher (who wants to publish the notice)-(nsdictionary *) UserInfo; Some additional information (informing the publisher of the content of the message sent to the notifying recipient)

3>.     Initializes a notification (nsnotification) object + (Instancetype) Notificationwithname: (NSString *) AName object: (ID) anobject;     + (Instancetype) Notificationwithname: (NSString *) AName object: (ID) anobject userInfo: (nsdictionary *) Auserinfo; -(Instancetype) Initwithname: (NSString *) Name object: (ID) object userInfo: (Nsdictionary *) UserInfo;

4>. Notification hubs (Nsnotificationcenter) provides the appropriate method to publish notifications        -(void) Postnotification: (nsnotification *) notification; //Publish a notification notification, you can set the name of the notification in the notification object, notify the Publisher, additional information, etc.        -(void) Postnotificationname: (NSString *) AName object: (ID) anobject;  //Publish a notification named Aname, anobject for this notification publisher        -(void) postnotificationname :(NSString *) AName object: (ID) anobject userInfo: (nsdictionary *) auserinfo; //Publish a notification called AName, AnObject is the publisher of this notification, auserinfo for additional information    

5>. Registration Notification Listener (OBSERVER)-(void) Addobserver: (ID) Observer selector: (SEL) aselector name: (NSString *) AName object: (     ID) anobject; Observer: Listener, who wants to receive this notification             Aselector: After receiving the notification, This method of callback listener, and the notification object as a parameter incoming             aName: The name of the notification.     If nil, the listener will receive this notification regardless of the name of the notification             AnObject: Notifies the publisher. If both AnObject and Aname are nil, the listener receives all notifications    

6>. The unregister notification listener notification Hub does not hold the (retain) listener object, and the object that is registered in the notification hub must be unregistered before the object is released. Otherwise, the notification hub will still send a message to the listener when the corresponding notification appears again.     Because the corresponding listener object has been freed, it may cause the app to crash-(void) Removeobserver: (ID) observer;     -(void) Removeobserver: (ID) Observer name: (NSString *) AName object: (ID) anobject;  Generally unregister before the listener is destroyed (such as by adding the following code to the listener):-(void) Dealloc {//[super dealloc];     This sentence needs to be called in non-arc [[Nsnotificationcenter Defaultcenter] removeobserver:self]; }

7>. Selection of notifications and proxies

1). Common denominator

Communication between objects can be accomplished with notifications and proxies

2). Different points

Agent: One-to-two relationships (an object can only tell what happened to another 1 objects)

Notification: A Many-to-many relationship (an object can tell what happened to n objects, and 1 objects know what happened to n objects)

8. Keyboard notification Uikeyboardwillshownotification//keyboard is about to show uikeyboarddidshownotification//keyboard display is complete UIKEYBOARDWILLH Idenotification//keyboard is about to be hidden uikeyboarddidhidenotification//keyboard hidden over uikeyboardwillchangeframenotification//keyboard Position size is about to change uikeyboarddidchangeframenotification//keyboard position size changed with additional keyboard-related information (dictionary), the dictionary common key is as follows: Uikeyboardframeb   Eginuserinfokey//Keyboard First frame Uikeyboardframeenduserinfokey//keyboard final frame (after the animation is finished) Uikeyboardanimationdurationuserinfokey//Keyboard animation time Uikeyboardanimationcurveuserinfokey//Keyboard animation execution Rhythm (speed) 9. Other 1>. Child controls do not display an error-troubleshooting method

1). See if the added method is called

2). Frame is empty (no frame is set)

3). is hidden Yes

4). Alpha <=0.1

5). Not added to parent control

6). See if there are any of the above points in the Init method the frame that is obtained is 0-(void) layoutsubviews {[Super layoutsubviews];     This method is called when the control's frame is changed//the method is generally used to adjust the position of the child control} 2> Called when-(void) Didmovetosuperview {}//will be added to the parent view when it is added to the parent view-(void) Willmov Etosuperview: (UIView *) Newsuperview {}

3> Uitextfield Add left and right view Self.textField.leftView = [[UIView alloc] Initwithframe:cgrectmake (0, 0, 10, 0)];     Sets the display mode for the left view self.textField.leftViewMode = Uitextfieldviewmodealways;     Self.textField.rightView = [[UIView alloc] Initwithframe:cgrectmake (0, 0, 10, 0)]; Sets the display mode for the right view Self.textField.rightViewMode = Uitextfieldviewmodealways;

4>.     Setting the picture in BTN does not fill the entire imageView btn.imageView.contentMode = Uiviewcontentmodecenter;     Out of range picture do not cut//btn.imageView.clipsToBounds = no; Btn.imageView.layer.masksToBounds = NO;

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.