美文网首页
Swift| 基础语法(五)

Swift| 基础语法(五)

作者: 進无尽 | 来源:发表于2018-05-17 15:25 被阅读0次

    前言

    总结下 swift下的基础语法,里面涉及到:常量&变量、Swift中的数据类型、逻辑分支、循环、字符串相关、数组和字典、方法的书写调用等内容,考虑到阅读体验分多篇来展示,希望对大家学习swift有所帮助,同时也是对自己的一个总结。

    Swift| 基础语法(一)
    Swift| 基础语法(二)
    Swift| 基础语法(三)
    Swift| 基础语法(四)
    Swift| 基础语法(五)

    本文涉及:

    • 纯代码创建应用根试图
    • UILabel、UIButton、UIImageView的使用
    • UITableView的使用
    • UITableView的使用
    • 单例
    • 从相册选择照片或者拍照

    一、纯代码创建应用根试图

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // 创建UIWindow对象,并初始化该窗口的大小与主屏幕大小相同
        let rect : CGRect = UIScreen.main.bounds
        // 程序将创建的UIWindow对象赋值给该程序委托对象的window属性
        self.window = UIWindow(frame:rect)
        // 创建ViewController对象、并使用ViewController界面布局文件来
        // 初始化该视图控制器关联的用户界面
        let vc = ViewController()
        //通过控件加载视图
        //let vc = ViewController(nibName: "ViewController", bundle: nil)   bundle:nil];
        // 让该程序的窗口加载、并显示viewController视图控制器关联的用户界面
        self.window?.rootViewController = vc
        //设置背景颜色
        self.window?.backgroundColor = UIColor.white
        // 将该UIWindow对象设为主窗口、并显示出来
        self.window?.makeKeyAndVisible()
        return true
    }
    

    二、UILabel、UIButton、UIImageView的使用

        let mylabel = UILabel(frame:CGRect.init(x: 30, y: 100, width: 100, height: 30))
        mylabel.text = "标签"
        mylabel.backgroundColor = UIColor.orange
        mylabel.textColor = UIColor.black
        
        let but = UIButton.init(frame: CGRect.init(x: 30, y: 200, width: 50, height: 50))
        but.setTitle("按钮", for: .normal)
        but.backgroundColor = UIColor.gray
        but.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
        
        let imageV = UIImageView.init(frame: CGRect.init(x: 30, y: 300, width: 80, height: 80))
        imageV.image = UIImage.init(named: "xixi")
        
        let sc = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height));
        sc.contentSize = CGSize.init(width: UIScreen.main.bounds.width, height: 1000)
        self.view.addSubview(sc)
        
        sc.addSubview(mylabel)
        sc.addSubview(but)
        sc.addSubview(imageV)
    
      //  按钮的点击事件
      @objc func buttonClick(_ button:UIButton) -> () {
            let butTitle:String = button.title(for: .normal)!
            print("按钮点击了: \(butTitle)")
        }
    

    三、UITableView的使用

    var myTb : UITableView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "Tb 测试"
        myTb = UITableView.init(frame: UIScreen.main.bounds)
        myTb?.dataSource = self
        myTb?.delegate = self
        myTb?.backgroundColor = UIColor.white
        view.addSubview((myTb)!)
        myTb?.tableFooterView = UIView()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let indentifier = "myCell"
        var cell:MyNewTableViewCell? = tableView.dequeueReusableCell(withIdentifier: indentifier) as? MyNewTableViewCell
        if cell == nil {
            //自定义cell使用此方法
            cell = MyNewTableViewCell(style: .subtitle, reuseIdentifier: "cellId")
            //xib加载cell使用此方法
            // cell = Bundle.main.loadNibNamed("testCell", owner: nil, options: nil)?.last as? UITableViewCell
        }
        cell?.label1?.text = "label1 :\(indexPath.row)"
        cell?.label2?.text = "label2 :\(indexPath.row)"
        return cell!
    }
    

    在Swift中,创建tableViewCell的方法可以分为两种创建tableView时候注册和需要使用时手动创建。先聊聊创建tableView的时候直接注册cell:

    myTb?.register(MyNewTableViewCell.self, forCellReuseIdentifier: "myCell")
    

    当注册了Cell之后,在没有可重用的Cell时会自动创建,并且不能在需要时手动创建。

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //创建cell,不需要判断是否为空,当没有可重用cell的时候会自动创建
        let cell:MyNewTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as? MyNewTableViewCell)!
        cell.label1?.text = "label1 :\(indexPath.row)"
        cell.label2?.text = "label2 :\(indexPath.row)"
        return cell
    }
    
    可以在自定义cell中处理点击状态下的显示
    var label1 :UILabel?
    var label2 :UILabel?
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        label1 = UILabel.init(frame: CGRect.init(x: 20, y: 10, width: 80, height: 20))
        label2 = UILabel.init(frame: CGRect.init(x: 20, y: 30, width: 80, height: 20))
        contentView.addSubview(label1!)
        contentView.addSubview(label2!)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //点击情况下的显示处理
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    
        if selected == true {
            contentView.backgroundColor = UIColor.yellow
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
                self.contentView.backgroundColor = UIColor.white
            }
        }
       
    }
    

    四、UITabBarController的使用

     func rootTabbarViewController() -> UITabBarController {
        
        // 首页
        let vc01 = ViewController()
        vc01.title = "首页"
        let nav01 = UINavigationController(rootViewController: vc01)
        // 发现
        let vc02 = UIViewController()
        vc02.title = "发现"
        let nav02 = UINavigationController(rootViewController: vc02)
        
        // 设置标题,未选中状态图标,选中状态图标
        let barItem01 = UITabBarItem(title: nil, image: UIImage(named: "TabBarItem_nomal_0")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "TabBarItem_light_0")?.withRenderingMode(.alwaysOriginal))
        vc01.tabBarItem = barItem01
        let barItem02 = UITabBarItem(title: nil, image: UIImage(named: "TabBarItem_nomal_1")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "TabBarItem_light_1")?.withRenderingMode(.alwaysOriginal))
        vc02.tabBarItem = barItem02
        
        let tabbarController = UITabBarController()
        tabbarController.tabBar.barTintColor = UIColor.white
        // 注意:视图控制器超过5个时(不包含5)会自动生成一个more视图标签,用来控制第5、6、...以后的视图控制器。
        tabbarController.viewControllers = [nav01, nav02]
        // 属性设置
        // 设置默认被选中视图控制器
        tabbarController.selectedIndex = 0;
        // 设置切换视图 tabBar 属性
        // 1 打开用户交互
        tabbarController.tabBar.isUserInteractionEnabled = true;
        // 2 设置背景颜色
        tabbarController.tabBar.backgroundColor = UIColor.black
        tabbarController.tabBar.barTintColor = UIColor.white
    //        // 3 设置背景图片
    //        tabbarController.tabBar.backgroundImage = UIImage(named: "")
    //        // 4 选中时的背景图片
    //        tabbarController.tabBar.selectionIndicatorImage = UIImage(named: "")
        
        // 设置字体颜色
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.gray], for: UIControlState.normal)
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.green], for: UIControlState.selected)
        // 设置字体大小
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont.systemFont(ofSize: 10.0)], for: UIControlState.normal)
        // 设置字体偏移
        //   UITabBarItem.appearance().titlePositionAdjustment = UIOffsetMake(0.0, -5.0)
        // 设置图标选中时颜色
        UITabBar.appearance().tintColor = UIColor.clear
    
        return tabbarController
    }
    

    这里特别说明下:默认未选中标签的图片和文字是灰色的,选中的是蓝色的,下面修改成橙色:

     //图片文字一起变色
     self.tabBar.tintColor = UIColor.orangeColor()
    

    如何显示原始图片的颜色和图案? .imageWithRenderingMode(.AlwaysOriginal) 即可。

    五、单例

    class AppManager {
    private static let _sharedInstance = AppManager()
     
    class func getSharedInstance() -> AppManager {
        return _sharedInstance
    }
      private override init() {} // 私有化init方法
    }
    
    //使用方式
    AppManager.getSharedInstance()
    
    
    为什么需要保证INIT的私有化? 
    
    因为只有init()是私有的,才能防止其他对象通过默认构造函数直接创建这个类对象,确保你的单例是真正的独一无二。 
    因为在Swift中,所有对象的构造器默认都是public,所以需要重写你的init让其成为私有的。
    这样就保证像如下的代码编译报错,不能通过。
    

    六、从相册选择照片或者拍照

    import UIKit
    
    class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
        
        var uploadAlertController : UIAlertController?
        var pick:UIImagePickerController?
        var imageV :UIImageView?
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            self.view.backgroundColor = UIColor.gray
            
            imageV = UIImageView.init(frame: CGRect.init(x: 30, y: 300, width: 80, height: 80))
            self.view.addSubview(imageV!)
            initAlertController()
            tapImage()
           
        }
        func initAlertController()
        {
            weak var blockSelf = self
            uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertControllerStyle.actionSheet)
            let takePhoto = UIAlertAction(title:"拍照", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
                blockSelf?.actionAction(action: action)
            }
            let photoLib = UIAlertAction(title:"从相册选择", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
                blockSelf?.actionAction(action: action)
            }
            let cancel = UIAlertAction(title:"取消", style:UIAlertActionStyle.cancel) { (action:UIAlertAction)in
                blockSelf?.actionAction(action: action)
            }
            uploadAlertController?.addAction(takePhoto)
            uploadAlertController?.addAction(photoLib)
            uploadAlertController?.addAction(cancel)
        }
        func tapImage(){
            present(uploadAlertController!, animated:true, completion: nil)
            initImagePickerController()
        }
        func initImagePickerController()
        {
            pick = UIImagePickerController()
            pick?.delegate = self
            // 设置是否可以管理已经存在的图片或者视频
            pick?.allowsEditing = true
        }
        func actionAction(action:UIAlertAction)
        {
            if action.title == "拍照" {
                self.getImageFromCamera(type: .camera)
            }else if action.title == "从相册选择" || action.title == "更换头像" {
                self.getImageFromPhotoLib(type: .photoLibrary)
            }
        }
        //拍照
        func getImageFromCamera(type:UIImagePickerControllerSourceType)
        {
            
            pick?.sourceType = type
            self.present(pick!, animated: true, completion:nil)
        }
        //相册选择
        func getImageFromPhotoLib(type:UIImagePickerControllerSourceType)
        {
            pick?.sourceType = type
            self.present(pick!, animated: true, completion:nil)
        }
        //MARK:- UIImagePickerControllerDelegate
        func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]){
            
            let type:String = (info[UIImagePickerControllerMediaType]as!String)
            //当选择的类型是图片
            if type == "public.image"
            {
                let img = info[UIImagePickerControllerOriginalImage]as?UIImage
                imageV?.image = img
            }
            picker.dismiss(animated:true, completion:nil)
        }
        
        func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
            picker.dismiss(animated:true, completion:nil)
        }
        
    }

    相关文章

      网友评论

          本文标题:Swift| 基础语法(五)

          本文链接:https://www.haomeiwen.com/subject/thyddftx.html