Swift's TableView cell image width fixed, highly adaptive example

Source: Internet
Author: User
Tags constant uikit
1, Sample Effect chart
(1) The cell above is the text, below is the picture.
(2) The number of text label (Uilabel) lines is self growing.
(3) Picture display (Uiimageview) width of the full line, height with the original proportion of adaptive height.
(4) The whole cell is highly adaptive and can fully display all the contents.

2, to achieve the steps
(1) We first create a custom cell class (Imagetableviewcell.swift) and create its corresponding XIB file (imagetableviewcell.xib).

(2) Open imagetableviewcell.xib, add a Label inside (to display the caption text), and a imageview (used to display the content picture). And do the associated reference in the corresponding class.
(3) to allow the label label to grow automatically, set its Lines property to 0.
(4) Set up or down 4 constraints on the Label.

(5) Set the next 3 constraints on the ImageView.

(6) Imagetableviewcell.swift code
When the above constraint is set, the width of the imageview is fixed. To make it highly adaptive, we need to dynamically set the ImageView ratio constraint in code by getting the aspect ratio of the interior display picture. Make sure the ImageView is the same as the original picture.

Import Uikit

Class Imagetableviewcell:uitableviewcell {

Title text label
@IBOutlet weak var titlelabel:uilabel!

Content picture
@IBOutlet weak var contentimageview:uiimageview!

Width-height ratio constraints for content pictures
Internal Var aspectconstraint:nslayoutconstraint? {
Didset {
If OldValue!= Nil {
Contentimageview.removeconstraint (oldvalue!)
}
If Aspectconstraint!= Nil {
Contentimageview.addconstraint (aspectconstraint!)
}
}
}

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

Override Func Prepareforreuse () {
Super.prepareforreuse ()
Clear the aspect ratio constraint for a content picture
Aspectconstraint = Nil
}


Load content picture (and set height constraint)
Func LoadImage (name:string) {

If let image = UIImage (named:name) {
Calculate the aspect ratio of the original picture
Let aspect = Image.size.width/image.size.height
Set the ImageView width-height ratio constraint
Aspectconstraint = Nslayoutconstraint (Item:contentimageview,
attribute:. Width, Relatedby:. Equal,
Toitem:contentimageview, attribute:. Height,
Multiplier:aspect, constant:0.0)
Load picture
Contentimageview.image = Image
}else{
Remove the ImageView in the picture and the width-height ratio constraint
Aspectconstraint = Nil
Contentimageview.image = Nil
}
}

Override Func setselected (Selected:bool, Animated:bool) {
Super.setselected (selected, animated:animated)

}
}

(7) Viewcontroller.swit
In the home page we create a tabbleview to test our custom cells above. There is nothing special here, similar to the previous article.

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", "img1.jpg"])
Catalog.append (["section II: Swift basic Syntax (type definition, looping traversal, judgment, inheritance)", "img2.jpg"])
Catalog.append (["section III: Swift data Type", "img3.jpg"])

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, style:. Plain)
Self.tableView.delegate = Self
Self.tableView.dataSource = Self

To create a reused cell
self.tableview!. Registernib (uinib (nibname: "Imagetableviewcell", Bundle:nil),
Forcellreuseidentifier: "MyCell")

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 {
Reuse of cells in the same form
Let cell = Tableview.dequeuereusablecellwithidentifier ("MyCell",
Forindexpath:indexpath) as! Imagetableviewcell
Get the corresponding entry contents
Let entry = Catalog[indexpath.row]
Cell Title and content settings
Cell.titleLabel.text = entry[0]
Cell.loadimage (Entry[1])

return cell
}

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

3, get pictures from the network

The example above we are loading the local picture directly. In the actual project, we usually load the pictures on the network through the URL address and display them.
Original: Swift-tableview Cell height Adaptive 3 (picture width fixed, highly adaptive)

Only need to make the following modifications to the Imagetableviewcell class to meet the requirements, the same support for the highly adaptive picture.


Import Uikit

Class Imagetableviewcell:uitableviewcell {

Title text label
@IBOutlet weak var titlelabel:uilabel!

Content picture
@IBOutlet weak var contentimageview:uiimageview!

Width-height ratio constraints for content pictures
Internal Var aspectconstraint:nslayoutconstraint? {
Didset {
If OldValue!= Nil {
Contentimageview.removeconstraint (oldvalue!)
}
If Aspectconstraint!= Nil {
Contentimageview.addconstraint (aspectconstraint!)
}
}
}

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

Override Func Prepareforreuse () {
Super.prepareforreuse ()
Clear the aspect ratio constraint for a content picture
Aspectconstraint = Nil
}


Load content picture (and set height constraint)
Func LoadImage (urlstring:string) {
Defining Nsurl Objects
Let URL = Nsurl (string:urlstring)
Get the data stream from the network, and then initialize the picture through the data stream
If let data = NSData (contentsofurl:url!), image = UIImage (data:data) {
Calculate the aspect ratio of the original picture
Let aspect = Image.size.width/image.size.height
Set the ImageView width-height ratio constraint
Aspectconstraint = Nslayoutconstraint (Item:contentimageview,
attribute:. Width, Relatedby:. Equal,
Toitem:contentimageview, attribute:. Height,
Multiplier:aspect, constant:0.0)
Load picture
Contentimageview.image = Image
}else{
Remove the ImageView in the picture and the width-height ratio constraint
Aspectconstraint = Nil
Contentimageview.image = Nil
}
}

Override Func setselected (Selected:bool, Animated:bool) {
Super.setselected (selected, animated:animated)

}
}
When used, change from the original picture name to the image URL address.


Initializing a list of data
Catalog.append (["IPhone 6 failure rate up to 26% stable Super Android", "Http://www.111cn.net/img1.png"])
Catalog.append (["Do not navigate this UAV can be" homemade "map Flight", "http://www.111cn.net/img2.png"])
Catalog.append (["How does an unmanned vehicle deal with moral dilemmas?") Google said not to know "," http://www.111cn.net/img33.png "])

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.