Swift零基础学习之用TableView做个景点App
2019-04-18 本文已影响44人
iCloudEnd
Swift零基础学习之用TableView做个景点App
视频播放地址:Swift零基础学习之用TableView做个景点App
-
创建一个新项目,我就叫Yanjing
-
将照片素材拖拽到Assets.xcassets中
-
添加navigation controller,点击editor->embed in >Navigation Controller
-
拖拽一个tableview,并配置constrain
-
拖拽一个tableview cell,并配置高度为90,custom
-
添加imageview 并配置constrain,左12,width 132,Vertically in container
-
添加label,并配置constrain,左12,右12,height 25,Vertically in container
-
创建一个swift文件,起名为JingDian,代码如下
import Foundation
import UIKit
class JingDian {
var image:UIImage
var title:String
init(image:UIImage, title:String ){
self.image = image
self.title = title
}
}
- 创建一个UITableViewCell ,命名为JingCell,具体代码如下
import UIKit
class JingCell: UITableViewCell {
func setVideo(jingDian: JingDian) {
jingImageView.image = jingDian.image
jingTitleLabel.text = jingDian.title
}
}
-
配置tablecell class,identifier为JingCell
-
添加IBOutlet,imageview 设置为jingImageView,label设置为jingTitleLabel
-
创建一个ViewController 名为JingListScreen,并配置对应class
-
将下面的代码复制到JingListScreen.swift文件上
//
// JingListScreen.swift
// Yanjing
//
// Created by cf on 2019/4/18.
// Copyright © 2019 cf. All rights reserved.
//
import UIKit
class JingListScreen: UIViewController{
@IBOutlet weak var tableView: UITableView!
var videos: [JingDian] = []
override func viewDidLoad() {
super.viewDidLoad()
videos = createArray()
}
func createArray() -> [JingDian] {
var objArray:[JingDian]=[]
let briefData = [
[
"title":"居庸叠翠",
"image":"001_jydc.jpg",
],
[
"title":"玉泉流虹(玉泉趵突)",
"image":"002_yqch.jpg",
],
[
"title": "太液晴波",
"image": "003_tyqf.jpg"
],
[
"title": "琼岛春云",
"image": "004_cqcy.jpg"
],
[
"title": "蓟门飞雨(蓟门烟树)",
"image": "005_jfys.jpg",
],
[
"title": "西山积雪",
"image": "006_xsjx.jpg"
],
[
"title": "卢沟晓月",
"image": "007_lgxy.jpg"
],
[
"title": "金台夕照",
"image": "008_jtxz.jpg"
],
]
for briefItem in briefData{
let videoItem=JingDian(
image: UIImage(imageLiteralResourceName:briefItem["image"]!),
title: briefItem["title"]!
)
objArray.append(videoItem)
}
return objArray
}
}
extension JingListScreen: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let video = videos[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "JingCell") as! JingCell
cell.setVideo(jingDian: video)
return cell
}
}
-
添加tableview的IBOutlet和delegate
-
设置一下imageview上下的间隔
-
运行App,查看效果