Swift TableView only 1 label label cells highly adaptive

Source: Internet
Author: User
Tags uikit

1, Cell height adaptive

Sometimes we use tables (UITableView) to display list data. You don't want each cell's height to be fixed, and it's best to customize the height of the cell according to its contents. In the past, if we wanted to display variable height dynamic content in table view, it would be troublesome to manually compute the row height.
Since IOS8, UITableView has added a new feature: Self sizing Cells. The table will automatically calculate the size of the cell and render it, greatly saving the development time.

2, conditions for using self sizing cells

(1) The cell cell needs to use the Auto Layout constraint.
(2) You need to specify the default value of the TableView Estimatedrowheight property.
(2) Set the TableView RowHeight property to Uitableviewautomaticdimension.

3, Sample Effect chart

The following is a simple example of how to use Self sizing Cells. Cell is the most primitive uitableviewcell, that is, there is only one text inside


4, sample code

Notice here that we want to set the NumberOfLines property of the cell label to 0 (the default is 1). This allows the label to grow automatically.


Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {

var catalog = [[String]] ()
var tableview:uitableview!

Override Func Viewdidload () {
Super.viewdidload ()

Initializing a list of data
Catalog.append (["section I: Swift environment set-up",
"As the swift development environment needs to run on the OS X system, let's take a look at how the swift development environment is built." "])
Catalog.append (["section II: Swift basic Syntax",
"This section describes some of the commonly used keywords in swift. As well as the introduction, annotation and other related operations. "])
Catalog.append (["section III: Swift data Type",
"Swift provides a wealth of data types, such as Int, UInt, floating-point numbers, Boolean values, strings, characters, and so on." "])
Catalog.append ([section Fourth: Swift variable ",
"Swift each variable specifies a specific type that determines the size of the variable's footprint." "])
Catalog.append ([Fifth Quarter: Swift Optional (optionals) type ",
"Swift's optional (Optional) type for handling value deletions. "])

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
Self.tableView.delegate = Self
Self.tableView.dataSource = Self
To create a reused cell
Self.tableView.registerClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")

Set the default value for the Estimatedrowheight property
Self.tableView.estimatedRowHeight = 44.0;
The RowHeight property is set to Uitableviewautomaticdimension
Self.tableView.rowHeight = uitableviewautomaticdimension;

Self.view.addSubview (self.tableview!)
}


In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.catalog.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell
Get the corresponding entry contents
Let entry = Catalog[indexpath.row]
Allow labels to grow automatically
Cell.textlabel? NumberOfLines = 0
Cell.textlabel? Text = "\ (entry[0]): \ (entry[1])"
return cell
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

5, function improvement

In the previous example, each section title and description of the content are not very attractive. The following is the Textlabel Attributedtext property to set a string with style attributes. Make the title text bold and color, and the introduction of the content begins to appear on a different line.

Import Uikit

Class Viewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {

var catalog = [[String]] ()
var tableview:uitableview!

Override Func Viewdidload () {
Super.viewdidload ()

Initializing a list of data
Catalog.append (["section I: Swift environment set-up",
"As the swift development environment needs to run on the OS X system, let's take a look at how the swift development environment is built." "])
Catalog.append (["section II: Swift basic Syntax",
"This section describes some of the commonly used keywords in swift. As well as the introduction, annotation and other related operations. "])
Catalog.append (["section III: Swift data Type",
"Swift provides a wealth of data types, such as Int, UInt, floating-point numbers, Boolean values, strings, characters, and so on." "])
Catalog.append ([section Fourth: Swift variable ",
"Swift each variable specifies a specific type that determines the size of the variable's footprint." "])
Catalog.append ([Fifth Quarter: Swift Optional (optionals) type ",
"Swift's optional (Optional) type for handling value deletions. "])

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
Self.tableView.delegate = Self
Self.tableView.dataSource = Self
To create a reused cell
Self.tableView.registerClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")

Set the default value for the Estimatedrowheight property
Self.tableView.estimatedRowHeight = 44.0;
The RowHeight property is set to Uitableviewautomaticdimension
Self.tableView.rowHeight = uitableviewautomaticdimension;

Self.view.addSubview (self.tableview!)
}


In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.catalog.count
}

Create each cell display (create a parameter indexpath a specified cell)
Func TableView (Tableview:uitableview, Cellforrowatindexpath Indexpath:nsindexpath)
-> UITableViewCell
{
In order to provide tabular display performance, the completed cells need to be reused
Let identify:string = "Swiftcell"
Cells in the same form are reused and registered at the time of declaration
Let cell = Tableview.dequeuereusablecellwithidentifier (Identify,
Forindexpath:indexpath) as UITableViewCell
Get the corresponding entry contents
Let entry = Catalog[indexpath.row]
Allow labels to grow automatically
Cell.textlabel? NumberOfLines = 0
Using attribute text
Cell.textlabel? Attributedtext = getattributedstring (Title:entry[0],
SUBTITLE:ENTRY[1])
return cell
}

Get Item Property Text
Func getattributedstring (title title:string, subtitle:string)-> nsattributedstring {
Title Font style
Let Titlefont = Uifont.preferredfontfortextstyle (uifonttextstyleheadline)
Let Titlecolor = Uicolor (red:45/255, green:153/255, blue:0/255, alpha:1)
Let titleattributes = [Nsfontattributename:titlefont,
Nsforegroundcolorattributename:titlecolor]
Introduction to Font Styles
Let Subtitlefont = Uifont.preferredfontfortextstyle (uifonttextstylesubheadline)
Let subtitleattributes = [Nsfontattributename:subtitlefont]
Stitching and getting final text
Let titlestring = nsmutableattributedstring (string: "\ (title) \ n",
Attributes:titleattributes)
Let subtitlestring = nsattributedstring (String:subtitle,
Attributes:subtitleattributes)
Titlestring.appendattributedstring (subtitlestring)
Return titlestring
}

Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}

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.