iOS开发:各项控件的简单运用(Swift)

运行的结果是一个类似Hduin首页的UI,需要用到的控件有:UITableView、UITableViewCell、UIScrollView、UITabbar等,需要用到第三方库Snapkit。

//
//  AppDelegate.swift
//
//  Created by louyu on 2018/11/25.
//  Copyright © 2018 louyu. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        /*
        let screen = UIScreen.main.bounds
        self.window = UIWindow.init(frame: screen)
        let viewController = ViewController()
        let navigationViewController = UINavigationController.init(rootViewController: viewController)
        self.window?.backgroundColor = UIColor.white
        self.window?.rootViewController = navigationViewController
        self.window?.makeKeyAndVisible()
        */
      self.window?.rootViewController = UINavigationController(rootViewController: tabBarController())
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

//
//
//  ViewController.swift
//
//  Created by louyu on 2018/12/11.
//  Copyright © 2018 louyu. All rights reserved.
//

import UIKit
import SnapKit



class ViewController:UIViewController,UITableViewDataSource,UITableViewDelegate {
    let pageControl = UIPageControl()
    let autoScrollView = UIScrollView()
    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    var a=[1,2,3,4,5,6,7,8,9,10]
        override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController?.title = "主页"
      //   self.navigationItem.title = "主页"
            autoScrollView.frame=CGRect(x: 0, y:self.tabBarController!.tabBar.frame.size.height+UIApplication.shared.statusBarFrame.size.height-5, width: screenWidth, height: 175)
        autoScrollView.contentSize = CGSize(width: autoScrollView.frame.width*5, height: autoScrollView.frame.height)
        autoScrollView.contentOffset=CGPoint(x:CGFloat(2)*autoScrollView.frame.width,y:0)
        autoScrollView.isPagingEnabled = true
        autoScrollView.bounces = true
        autoScrollView.showsHorizontalScrollIndicator=false
        autoScrollView.delegate = self
        view.addSubview(autoScrollView)
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: autoScrollView.frame.maxY, width: screenWidth, height: screenHeight-autoScrollView.frame.maxY)
        tableView.backgroundColor = UIColor.white;
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self

        for i in 1...5 {
            let imageView = UIImageView(frame: CGRect(x: autoScrollView.frame.width*CGFloat(i-1), y: 0, width: autoScrollView.frame.width, height: autoScrollView.frame.height))
            imageView.image = UIImage(named: "\(i).jpg")
            autoScrollView.addSubview(imageView)
        }
       // pageControl.frame = CGRect(x: 0, y: 475, width: 375, height: 50)
       // pageControl.backgroundColor = UIColor.gray
        pageControl.numberOfPages = 5
        pageControl.currentPage = 2
       // pageControl.addTarget(self, action: #selector(pageControlClick), for: .valueChanged)
    }
    
    //MARK: UITableViewDataSource
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"
        var cell:NewTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? NewTableViewCell
        if cell==nil {
            cell = NewTableViewCell(style: .subtitle, reuseIdentifier: cellid)
        }
        cell?.iconImv.image = UIImage(named: "Picture")
        cell?.titleLabel.text = "\(a[indexPath.row])"
        cell?.sourceLabel.text = "666"
        return cell!
    }
    
    //MARK: UITableViewDelegate
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }
 
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0{
        let secondVC=ViewController2()
        self.navigationController!.pushViewController(secondVC,animated:true)
        }
        if indexPath.row == 1{
            let thirdVC=ViewController3()
            self.navigationController!.pushViewController(thirdVC,animated:true)
        }

    }
    /*
    @objc func pageControlClick(pageControl:UIPageControl) {
        UIView.animate(withDuration: 0.3) {
            self.autoScrollView.contentOffset = CGPoint(x: CGFloat(pageControl.currentPage)*self.autoScrollView.frame.size.width, y: 0)
        }
    }*/
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 函数floor的作用是返回比小的整数,比如floor(1.2312) = 1
        let page = floor((autoScrollView.contentOffset.x)/autoScrollView.frame.size.width)
        pageControl.currentPage = Int(page)
        
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if (pageControl.currentPage==0)
        {
            pageControl.currentPage=3
            autoScrollView.contentOffset=CGPoint(x:CGFloat(3)*autoScrollView.frame.width,y:0)
        }
        if (pageControl.currentPage==4)
        {
            pageControl.currentPage=1
            autoScrollView.contentOffset=CGPoint(x:CGFloat(1)*autoScrollView.frame.width,y:0)
        }
    }
   
}

//
//  NewTableViewCell.swift
//
//  Created by louyu on 2018/11/27.
//  Copyright © 2018 louyu. All rights reserved.
//

import UIKit
import SnapKit

class NewTableViewCell: UITableViewCell {
    
    let width:CGFloat = UIScreen.main.bounds.width
    var titleLabel:UILabel!      // 标题
    var sourceLabel:UILabel!  // 来源
    var iconImv:UIImageView!    // 图片
    
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 图片
        iconImv = UIImageView()
        contentView.addSubview(iconImv)
        iconImv.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.bottom.equalTo(-10)
            make.right.equalTo(-20)
            make.left.equalTo(280)
        }
        
        // 标题
        titleLabel = UILabel()
        titleLabel.textColor = UIColor.black
        titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints{(make)in
            make.top.equalTo(20)
            make.bottom.equalTo(-60)
            make.left.equalTo(40)
        }
        
        
        // 来源
        sourceLabel = UILabel()
        sourceLabel.textColor = UIColor.gray
        sourceLabel.font = UIFont.systemFont(ofSize: 13)
        contentView.addSubview(sourceLabel)
        sourceLabel.snp.makeConstraints{(make)in
            make.bottom.equalTo(-10)
            make.left.equalTo(40)
     
        }
        

    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

//
//  ViewController2.swift
//
//  Created by louyu on 2018/12/11.
//  Copyright © 2018 louyu. All rights reserved.
//

import UIKit

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "子界面1"
        view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

//
//  ViewController3.swift
//
//  Created by louyu on 2018/12/11.
//  Copyright © 2018 louyu. All rights reserved.
//

import UIKit

class ViewController3: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "子界面2"
        view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

//
//  tabBarController.swift
//
//  Created by louyu on 2018/12/11.
//  Copyright © 2018 louyu. All rights reserved.
//

import UIKit

class tabBarController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        let VC1 = ViewController()
        let VC2 = ViewController2()
        let VC3 = ViewController3()
        
        VC1.tabBarItem.title = "主页"
        VC2.tabBarItem.title = "子界面1"
        VC3.tabBarItem.title = "子界面2"
        
        
        
        self.viewControllers = [VC1, VC2, VC3]
        
       
    }
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        self.title = item.title
}

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注