Swift-基础

作者: 勇敢的_心_ | 来源:发表于2019-04-16 09:16 被阅读2次

    知识点

    宏定义

    无参数宏:
    //oc中的宏定义
    #define kIOS7   [UIDevice currentDevice].systemVersion.doubleValue>=7.0 ? 1 :0
    #define kIOS8   [UIDevice currentDevice].systemVersion.doubleValue>=8.0 ? 1 :0
    #define kScreenHeight     [UIScreen mainScreen].bounds.size.height
    #define kScreenWidth      [UIScreen mainScreen].bounds.size.width
    //转换成swift的写法
    let kIOS7 = Double(UIDevice().systemVersion)>=7.0 ? 1 :0
    let kIOS8 = Double(UIDevice().systemVersion)>=8.0 ? 1 :0
    let kScreenHeight = UIScreen.mainScreen().bounds.size.height
    let kScreenWidth = UIScreen.mainScreen().bounds.size.width
    
    有参数的宏:
    //oc写法
    #define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
    //swift中的写法
    func RGBCOLOR(r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor
    {
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: 1.0)
    }
    

    页面跳转

     window = UIWindow(frame: UIScreen.main.bounds)
     let homeVC = HomeViewController()
    let nav = UINavigationController(rootViewController : homeVC)
    window?.rootViewController = nav
    window?.makeKeyAndVisible()
    
    // present方式
    let assetsViewController = AssetsViewController()
    present(assetsViewController, animated: true, completion: nil)
    // dismiss返回
    dismiss(animated: true, completion: nil)
    
    // push方式
    self.navigationController?.pushViewController(AssetsViewController(), animated: true)
    // pop返回
    self.navigationController?.popViewController(animated: true)
    

    字符串

    1.遍历字符串
    let str = "hello world"
            for c in str.characters{
                print(c)
            }
    
    2.拼接字符串
            let str1 = "hello"
            let str2 = "world"
            let str3 = str1+str2
            let info = "my name is\(str)"
    
    3.字符串截取
            let header = (str as NSString).substring(to: 3)
            let body = (str as  NSString).substring(with:NSRange(location:4,length:3))
            let bodyy = (str as NSString).substring(from: 4)
    

    控件

    UILabel

    let label = UILabel(frame:CGRect(x:10, y:20, width:300, height:100))
            label.text = "hangge.com"
            self.view.addSubview(label)
    
    背景颜色和文字颜色的设置
    label.textColor = UIColor.white //白色文字
    label.backgroundColor = UIColor.black //黑色背景
    
    对齐方式的设置
    label.textAlignment = .right//文字右对齐
    
    文字阴影的设置
    label.shadowColor = UIColor.gray  //灰色阴影
    label.shadowOffset = CGSize(width:1.5, height:1.5)  //阴影的偏移量
    
    字体的设置
    label.font = UIFont(name:"Zapfino", size:20)
    
    文字过长时的省略方式
    label.lineBreakMode = .byTruncatingTail  //隐藏尾部并显示省略号
    label.lineBreakMode = .byTruncatingMiddle  //隐藏中间部分并显示省略号
    label.lineBreakMode = .byTruncatingHead  //隐藏头部并显示省略号
    label.lineBreakMode = .byClipping  //截去多余部分也不显示省略号
    
    文字大小自适应标签宽度
    label.adjustsFontSizeToFitWidth = true //当文字超出标签宽度时,自动调整文字大小,使其不被截断
    
    使标签可以显示多行文字
    label.numberOfLines = 2  //显示两行文字(默认只显示一行,设为0表示没有行数限制)
    
    设置文本高亮
    //设置文本高亮
    label.isHighlighted = true
    //设置文本高亮颜色
    label.highlightedTextColor = UIColor.green
    
    富文本设置
    //富文本设置
    let attributeString = NSMutableAttributedString(string:"感谢18888位用户的信任,累积交易额达\n 22222266666元")
    // 颜色        attributeString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red,range: NSMakeRange(2,5))
    // 大小
    attributeString.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(20,13))
    Label.attributedText = attributeString
    

    UIImageView

    let imageView = UIImageView(image:UIImage(named:"image1"))
    imageView.frame = CGRect(x:10, y:30, width:300, height:150)
    self.view.addSubview(imageView)
    
    改变图片
    imageView.image = UIImage(named:"icon2")
    
    从文件目录中获取图片
    let path = Bundle.main.path(forResource: "ball", ofType: "png")
    let newImage = UIImage(contentsOfFile: path!)
    let imageView = UIImageView(image:newImage)
    self.view.addSubview(imageView)
    
    从网络地址获取图片
    //定义URL对象
    let url = URL(string: "http://hangge.com/blog/images/logo.png")
    //从网络获取数据流
    let data = try! Data(contentsOf: url!)
    //通过数据流初始化图片
    let newImage = UIImage(data: data)
    let imageView = UIImageView(image:newImage);
    self.view.addSubview(imageView)
    
    保持图片比例 :
    imageView.contentMode = .scaleAspectFit
    
    使用图像控件实现动画播放
    UIImageView 中提供了存储多张图片来创建动画的功能,具体做法是,在 animationImages 属性中设置一个图片数组,然后使用 startAnimating 方法开始动画,最后用 stopAnimating 方法停止动画。同时,使用 animationDuration 属性中可以设置动画每帧切换的速度(秒)。
    
    var imageView:UIImageView!
        override func viewDidLoad() {
            super.viewDidLoad()
            imageView = UIImageView()
            imageView.frame=CGRect(x:20, y:20, width:100, height:100)
            //设置动画图片
            imageView.animationImages = [UIImage(named:"icon1")!,UIImage(named:"icon2")!]
            //设置每隔0.5秒变化一次
            imageView.animationDuration=0.5
            self.view.addSubview(imageView)
        }
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            imageView.startAnimating()
        }
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillAppear(animated)
            imageView.stopAnimating()
        }
    

    UIButton

    按钮有下面四种类型:
        UIButtonType.system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
        UIButtonType.custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
        UIButtonType.contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
        UIButtonType.detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
        UIButtonType.infoDark:为感叹号“!”圆形按钮
        UIButtonType.infoLight:为感叹号“!”圆形按钮
    
    //创建一个ContactAdd类型的按钮
    let button:UIButton = UIButton(type:.contactAdd)
    //设置按钮位置和大小
    button.frame = CGRect(x:10, y:150, width:100, height:30)
    //设置按钮文字
    button.setTitle("按钮", for:.normal)
    self.view.addSubview(button)
    
    对于Custom定制类型按钮,代码可简化为:
    let button = UIButton(frame:CGRect(x:10, y:150, width:100, height:30))
    
    按钮的文字设置
    button.setTitle("普通状态", for:.normal) //普通状态下的文字
    button.setTitle("触摸状态", for:.highlighted) //触摸状态下的文字
    button.setTitle("禁用状态", for:.disabled) //禁用状态下的文字
    
    按钮文字颜色的设置
    button.setTitleColor(UIColor.black, for: .normal) //普通状态下文字的颜色
    button.setTitleColor(UIColor.green, for: .highlighted) //触摸状态下文字的颜色
    button.setTitleColor(UIColor.gray, for: .disabled) //禁用状态下文字的颜色
    
    按钮文字阴影颜色的设置
    button.setTitleShadowColor(UIColor.green, for:.normal) //普通状态下文字阴影的颜色
    button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通状态下文字阴影的颜色
    button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通状态下文字阴影的颜色
    
    按钮文字的字体和大小设置
    button.titleLabel?.font = UIFont.systemFont(ofSize: 11)
    
    按钮背景颜色设置
    button.backgroundColor = UIColor.black
    
    按钮文字图标的设置 :
    默认情况下按钮会被渲染成单一颜色
    button.setImage(UIImage(named:"icon1"),forState:.Normal)  //设置图标
    button.adjustsImageWhenHighlighted=false //使触摸模式下按钮也不会变暗(半透明)
    button.adjustsImageWhenDisabled=false //使禁用模式下按钮也不会变暗(半透明)
    
    也可以设置成保留图标原来的颜色
    let iconImage = UIImage(named:"icon2")?.withRenderingMode(.alwaysOriginal)
    button.setImage(iconImage, for:.normal)  //设置图标
    button.adjustsImageWhenHighlighted = false //使触摸模式下按钮也不会变暗(半透明)
    button.adjustsImageWhenDisabled = false //使禁用模式下按钮也不会变暗(半透明)
    
    设置按钮背景图片:
    button.setBackgroundImage(UIImage(named:"bg1"), for:.normal)
    
    按钮触摸点击事件响应:
    //不传递触摸对象(即点击的按钮)
    button.addTarget(self, action:#selector(tapped), for:.touchUpInside)
    func tapped(){
         print("tapped")
    }
    //传递触摸对象(即点击的按钮),需要在定义action参数时,方法名称后面带上冒号
    button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside)
    func tapped(_ button:UIButton){
         print(button.title(for: .normal))
    }
    
    touchDown:单点触摸按下事件,点触屏幕
    touchDownRepeat:多点触摸按下事件,点触计数大于1,按下第2、3或第4根手指的时候
    touchDragInside:触摸在控件内拖动时
    touchDragOutside:触摸在控件外拖动时
    touchDragEnter:触摸从控件之外拖动到内部时
    touchDragExit:触摸从控件内部拖动到外部时
    touchUpInside:在控件之内触摸并抬起事件
    touchUpOutside:在控件之外触摸抬起事件
    touchCancel:触摸取消事件,即一次触摸因为放上太多手指而被取消,或者电话打断
    
    按钮文字太长时的处理方法:
    默认情况下,如果按钮文字太长超过按钮尺寸,则会省略中间的文字。比如下面代码:
    let button = UIButton(frame:CGRect(x:20, y:50, width:130, height:50))
    button.setTitle("这个是一段 very 长的文字", for:.normal) //普通状态下的文字
    button.setTitleColor(UIColor.white, for: .normal) //普通状态下文字的颜色
    button.backgroundColor = UIColor.orange
    self.view.addSubview(button)
    
    //省略尾部文字
    button.titleLabel?.lineBreakMode = .byTruncatingTail
    

    UIAlertController

    // 弹出
     let alertController = UIAlertController(title:"联系方式",message:"185-5242-8862",preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "确定", style: .default, handler:{
                (UIAlertAction) -> Void in
                print("点击确定事件")
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
    
    // 上滑
    let alertController = UIAlertController(title: "保存或删除数据", message: "删除数据将不可恢复",
                                                    preferredStyle: .actionSheet)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let deleteAction = UIAlertAction(title: "删除", style: .destructive, handler: nil)
            let archiveAction = UIAlertAction(title: "保存", style: .default, handler: nil)
            alertController.addAction(cancelAction)
            alertController.addAction(deleteAction)
            alertController.addAction(archiveAction)
            self.present(alertController, animated: true, completion: nil)
    
    //按钮使用“告警”样式
    let okAction = UIAlertAction(title: "好的", style: .destructive, handler: nil)
    
    //添加任意数量文本输入框
      let alertController = UIAlertController(title: "系统登录",
                                message: "请输入用户名和密码", preferredStyle: .alert)
            alertController.addTextField {
                (textField: UITextField!) -> Void in
                textField.placeholder = "用户名"
            }
            alertController.addTextField {
                (textField: UITextField!) -> Void in
                textField.placeholder = "密码"
                textField.isSecureTextEntry = true
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            let okAction = UIAlertAction(title: "好的", style: .default, handler: {
                action in
                //也可以用下标的形式获取textField let login = alertController.textFields![0]
                let login = alertController.textFields!.first!
                let password = alertController.textFields!.last!
                print("用户名:\(login.text) 密码:\(password.text)")
            })
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
    
    // 使用代码移除提示框
    self.presentedViewController?.dismiss(animated: false, completion: nil)
    
    // 提示框弹出后,过段时间自动移除
    let alertController = UIAlertController(title: "保存成功!",
                                            message: nil, preferredStyle: .alert)
    self.present(alertController, animated: true, completion: nil)
    //两秒钟后自动消失
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
        self.presentedViewController?.dismiss(animated: false, completion: nil)
    }
    

    UITableView

    // tableView
            let tableView = UITableView(frame:UIScreen.main.bounds)
            tableView.backgroundColor = UIColor.darkGray
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(UINib (nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
            view.addSubview(tableView)
    // tableView-headView
            let headView : UIView = UIView(frame:CGRect(x:0,y:0,width:screenW,height:120))
            headView.backgroundColor = UIColor.yellow
            tableView.tableHeaderView = headView
     // tableView - footView
            tableView.tableFooterView = UIView()
    

    UINavigationController

    let navgationController = UINavigationController(rootViewController: viewC);
    //设置导航栏的统一的背景色
    
      UINavigationBar.appearance().barTintColor = UIColor.blueColor();
    // 设置导航栏的背景色
    
    navgationController.navigationBar.barTintColor = UIColor.yellowColor();
    //设置导航栏的样式
    
    navgationController.navigationBar.barStyle = UIBarStyle.BlackTranslucent;
    //设置导航栏透明
    
    navgationController.navigationBar.translucent = true;
    //设置导航栏的背景图
    
     navgationController.navigationBar.setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default);
    //获取控制器中最顶端的视图
    
      let topViewC = self.navigationController?.topViewController;
    //获取控制器当前显示的视图
    
     let currentViewC = self.navigationController?.visibleViewController;
    //获取当前控制器所有的子视图
    
    let viewAarray = self.navigationController?.viewControllers;
    //设置prompt属性,主要是用来做一些提醒,比如网络请求,数据加载等等
    
     self.navigationItem.prompt = "正在加载数据";
    //不用时,将prompt属性置为nil即可,自带动画效果哦
      self.navigationItem.prompt = nil;
    
    1,签订代理
    self.navigationController?.delegate = self;
    2,常用代理方法
    1):视图控制器将要显示时调用
    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
        
    }
    2):视图控制器已经显示时调用
    func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
        
    }
    四:自定义navigationBarItem
    navigationItem常用的属性
    
        //自定义左侧一个按钮时使用
        self.navigationItem.leftBarButtonItem
        //自定义左侧多个按钮时使用
        self.navigationItem.leftBarButtonItems
        //自定义右侧一个按钮时使用
        self.navigationItem.rightBarButtonItem
        //自定义右侧多个按钮时使用
        self.navigationItem.rightBarButtonItems
        //中间显示的标题文字
        self.navigationItem.title
      //自定义中间部分标题视图时使用
        self.navigationItem.titleView
    
    例如:
    let item = UIBarButtonItem(title: "done", style: UIBarButtonItemStyle.Done, target: self, action: "done:");
    self.navigationItem.leftBarButtonItem = item;
    UIBarButtonItem有三种创建方式
    1):带标题的
      public convenience init(title: String?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector)
    2):带图片的
      public convenience init(image: UIImage?, landscapeImagePhone: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) 
    3:带自定义视图的
    public convenience init(customView: UIView)
    

    实例

    UITableView

    1.xib创建cell:
    import UIKit
    class HomeViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            configHomeViewControllerUI()
            print("who are you ")
        }
    
        func configHomeViewControllerUI(){
            view.backgroundColor = UIColor.green
    
            let tableView = UITableView(frame:UIScreen.main.bounds)
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(UINib (nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
            view.addSubview(tableView)
            tableView.tableFooterView = UIView()
        }
    
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 12
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            let cell : HomeCell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeCell
            cell.name.text = "hello homecell"
            return cell
        }
    
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("present VC")
    self.navigationController?.pushViewController(AssetsViewController(), animated: true)
        }
    
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 60
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    
    
    2.自带cell样式:
    import UIKit
    class AssetsViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
        override func viewDidLoad() {
            super.viewDidLoad()
            configAssetsViewControllerUI()
        }
    
        func configAssetsViewControllerUI(){
    
            view.backgroundColor = UIColor.orange
    
            let tableView = UITableView(frame :UIScreen.main.bounds)
            tableView.dataSource = self
            tableView.delegate = self
            view.addSubview(tableView)
        }
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 15
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            let initIdentifier = "AssetsCell"
            let cell = UITableViewCell(style:UITableViewCellStyle.subtitle,reuseIdentifier:initIdentifier)
            cell.textLabel?.text = "who are you ?\(indexPath.row)"
            cell.detailTextLabel?.text = "Kitty"
            return cell
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift-基础

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