分类 iOS控件 下的文章

九宫格

//
//  ViewController.swift
//  九宫格
//
//  Created by admin on 15/12/26.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    //存放通知消息的lable
    lazy var lable:UILabel =
    {
        var lable = UILabel()
        //设置宽度
        lable.frame.size.width = 100
        //设置高度
        lable.frame.size.height = 20
        //设置位置
        lable.transform = CGAffineTransformMakeTranslation(UIScreen.mainScreen().bounds.size.width/2 - lable.frame.size.width/2, UIScreen.mainScreen().bounds.size.height/2)
        //设置背景颜色
        lable.backgroundColor = UIColor(red: 0.483992,green:0.638788,blue: 1, alpha: 1)
        //设置文字
        lable.text = "正在下载中........"
        //设置圆角,button可以设置,lable没有效果啊
        lable.layer.cornerRadius = 50
        return lable
    }()
    //当前最后一个插入主视图在数组中的下标
    var dataIndex:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        //获得图片信息
        let data = NSArray.init(contentsOfFile: NSBundle.mainBundle().pathForResource("app", ofType: "plist")!)
        //循环添加控件
        for (var (index,blockInfo)) in EnumerateSequence(data!)
        {
            //获得图片
            let image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource(String(blockInfo["icon"]!!), ofType: "png")!)
            //获得图片描述
            let descreption = String(blockInfo["name"]!!)
            //设置最后插入视图的数据的在数据数组中的下标
            self.dataIndex = index
            //执行插入
            addChildBlok(image!,description: descreption,dataIndex: self.dataIndex)
        }
    }
    //UIImage好像没有直接缩放的办法,就用这个完成缩放
    func scalImage(image:UIImage,scal:CGFloat)->UIImage
    {
        //创建 CGSize 对象记录下缩放改变比例之后的宽高,方便之后的使用
        let imageSize = CGSize(width: CGFloat(image.size.width*scal),height: CGFloat(image.size.height*scal))
        //创建一个 bitmap 大小的 context
        UIGraphicsBeginImageContext(imageSize)
        //绘制改变大小的图片
        image.drawInRect(CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
        //从当前context中创建一个改变大小后的图片
        let imageTest = UIGraphicsGetImageFromCurrentImageContext()
        //使当前 context 出栈
        UIGraphicsEndImageContext()
        return imageTest
    }
    func addChildBlok(image:UIImage,description:String,dataIndex:Int)
    {
        //列数是计算而成的,初始化是散列
        var column = 3
        //这里可以通过屏幕的宽度来选择显示多少条
        if UIScreen.mainScreen().bounds.size.width > 0
        {
            column = 4
        }

        //获得屏幕当前 view 的左边距
        var marginLeft = Int(UIScreen.mainScreen().bounds.size.width * 0.05)
        //上边距
        let marginTop = 20
        //获得 view 的宽度
        let blockViewWidth = Int(UIScreen.mainScreen().bounds.size.width * 0.8 / CGFloat(column))
        //重新设置左边距,以达到居中的效果
        marginLeft = (Int(UIScreen.mainScreen().bounds.size.width) - column * blockViewWidth) / 2


        //创建 view


        let blockView = UIView(frame: CGRect(x: 0,y: 0,width: 0,height: 0))

        //设置blockview颜色,用以调试
        //blockView.backgroundColor = UIColor(red:0.483992,green:0.638788,blue: 1,alpha: 1)
        self.view.addSubview(blockView)

        //获得图片信息
        var image = image
        let descreption = description
        //缩放图片
        image = scalImage(image, scal: (CGFloat(blockViewWidth) * 0.8)/image.size.width)

        //创建 UIImageView 承载图片
        let imageView = UIImageView(image: image)
        //改变UIImageView位置
        let imageMarginLeft = CGFloat((Double(blockViewWidth) * 0.1))
        let imageMarginTop = CGFloat((Double(blockViewWidth) * 0.1))
        imageView.transform = CGAffineTransformTranslate(imageView.transform, imageMarginLeft, imageMarginTop)

        //加入当前view中
        blockView.addSubview(imageView)


        //加入 UIlable ,并设定好坐标和大小
        let lableMarginLeft = imageMarginLeft
        let lableMarginTop = imageMarginTop + imageView.frame.height
        let lable = UILabel(frame: CGRect(x: lableMarginLeft,y: lableMarginTop,width: CGFloat((Double(blockViewWidth) * 0.8)),height: 10))
        //像这样直接创建一个,设置字体没有效果
        //lable.font = UIFont(name: "System", size: CGFloat(10))
        //改变字体的大小
        lable.font = lable.font.fontWithSize(8)
        //改变字体对齐方式
        lable.textAlignment = NSTextAlignment.Center
        //设置lable显示的文字
        lable.text = descreption
        blockView.addSubview(lable)

        //加入button并设定好位置信息
        let buttonMarginLeft = imageMarginLeft
        let buttonMarginTop = imageMarginTop + lable.frame.height + imageView.frame.height
        let button = UIButton(frame: CGRect(x: buttonMarginLeft,y: buttonMarginTop,width: CGFloat((Double(blockViewWidth) * 0.8)),height: 10))
        //设置背景图片
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Highlighted)
        //设置title
        button.setTitle("点击下载", forState: UIControlState.Normal)
        button.setTitle("正在下载", forState: UIControlState.Highlighted)
        //设置字体大小
        button.titleLabel?.font = button.titleLabel?.font.fontWithSize(7)
        //绑定事件
        button.addTarget(self, action: "showInfo:", forControlEvents: UIControlEvents.TouchDown)
        //设定当前view的坐标和大小
        let blockViewHeight = imageMarginTop + imageView.frame.height + lable.frame.height + button.frame.height
        let blockViewX = (dataIndex%column) * blockViewWidth + marginLeft
        let blovkViewY = (dataIndex/column) * Int(blockViewHeight) + marginTop
        blockView.frame = CGRectMake(CGFloat(blockViewX), CGFloat(blovkViewY), CGFloat(blockViewWidth), CGFloat(blockViewHeight))

        blockView.addSubview(button)

//        self.view.bringSubviewToFront(button)
        //出现一次情况,按钮点击之后没有任何反应,搞了半天,后来想到用这个办法调试,发现原来是button的位置不在父控件的view之内
//        blockView.backgroundColor = UIColor(red:0.483992,green:0.638788,blue: 1,alpha: 1)
//        imageView.backgroundColor = UIColor(red:0.12323,green:0.123123,blue: 1,alpha: 1)


    }
    //按钮点击事件,显示一个lable
    func showInfo(sender:UIButton)
    {
        //改变当前点击按钮的图片和文字,禁用点击
        sender.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Normal)
        sender.setTitle("正在下载", forState: UIControlState.Normal)
        sender.enabled = false
        //显示lable按钮
        self.view.addSubview(self.lable)
        //延时执行函数
        self.performSelector("hideInfo:", withObject: sender, afterDelay: 1)
    }
    //执行完毕,隐藏lable
    func hideInfo(button:AnyObject)
    {
        //设置lable透明度
        UIView.animateWithDuration(3, animations: {
            self.lable.alpha = 0
        })
        //延时执行函数,初始化执行完毕的信息
        self.performSelector("endDownload:", withObject: button, afterDelay: 3)
    }
    //进行下载完成之后的初始化
    func endDownload(button:UIButton)
    {
        //设置当前按钮的图片和文字,禁用点击
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("下载完成", forState: UIControlState.Normal)
        button.enabled = false
        //设置lable透明度
        self.lable.alpha = 1
        //移除lable
        self.lable.removeFromSuperview()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


swift版本的汤姆猫

//
//  ViewController.swift
//  汤姆猫
//
//  Created by admin on 15/12/25.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    //定义 UIImageView 变量
    var imageView:UIImageView = UIImageView()
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置imageView坐标,尺寸
        imageView.frame = CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: 280, height: 450))
        //设置imageView默认图片
        imageView.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("cymbal_00", ofType: "jpg")!)!
        //把imageView添加进主视图
        self.view.addSubview(self.imageView)
        addButton("cymbal",actionName: "cymbal",x:50,y:400)
        addButton("pie",actionName: "pie",x:100,y:400)
        // Do any additional setup after loading the view, typically from a nib.
    }
    //添加按钮方法
    func addButton(backgroundImage:String,actionName:String,x:CGFloat,y:CGFloat)
    {
        //添加按钮
        let cymbalButton = UIButton()
        let buttonBackgroundImage = UIImage(imageLiteral: backgroundImage)
        //设置按钮背景图片
        cymbalButton.setBackgroundImage(buttonBackgroundImage, forState: UIControlState())
        //设置按钮位置坐标和宽度高度
        cymbalButton.frame = CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: buttonBackgroundImage.size.width, height: buttonBackgroundImage.size.height))
        //绑定事件方法,带参数的方法要加上冒号
        cymbalButton.addTarget(self, action: Selector("\(actionName):"), forControlEvents: UIControlEvents.TouchDown)
        //添加进主视图
        self.view.addSubview(cymbalButton)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func cymbal(sender: AnyObject) {
        //执行动画
        doAnimatingImage(self.getAnimatingImage("cymbal_",startNumber:0,endNumber:12))
    }
    @IBAction func pie(sender: AnyObject) {
        doAnimatingImage(self.getAnimatingImage("pie_",startNumber:0,endNumber:23))
    }
    //获得图片资源
    func getAnimatingImage(imagePrefix:String,startNumber:Int,endNumber:Int)->[UIImage]
    {
        var imageArr:[UIImage] = []
        for var i = startNumber;i <= endNumber;i++
        {
            //不足两位用0补齐
            let imagePath = String(format: "%02i", i)
            //使用这个方式(imageLiteral)创建的图片会缓存在内存中,系统内存占用会很大
            //imageArr.append(UIImage(imageLiteral: "\(imagePrefix)\(imagePath)"))
            //这个方式创建的图片不会缓存在内存中,但是要注意,图片不能放在.xcassets文件中,.xcassets中的文件都是经过处理的,不能像这样取得
            imageArr.append(UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("\(imagePrefix)\(imagePath)", ofType: "jpg")!)!)
        }
        return imageArr
    }

    //播放动画
    func doAnimatingImage(imageArr:[UIImage])
    {
        //当前正在执行动画的时候,不响应动作
        if imageView.isAnimating() == false
        {
            //设置帧动画图片数组
            imageView.animationImages = imageArr
            //设置重复次数,默认是执行无数次,这里设置成1次
            imageView.animationRepeatCount = 1
            //设置动画执行时间
            imageView.animationDuration = NSTimeInterval(Double(imageArr.count) * 0.07)
            //开始执行动画
            imageView.startAnimating()
            //动画之行完毕之后释放内存,这个函数是延时执行的
            self.performSelector(Selector("clearAnimetingImage"), withObject: nil, afterDelay: imageView.animationDuration)
        }
    }
    //清除对UIImage数组的强引用,释放内存
    func clearAnimetingImage()
    {
        imageView.animationImages = nil
    }

}

图片浏览器

//
//  ViewController.swift
//  图片浏览器
//
//  Created by admin on 15/12/24.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var preButton: UIButton!
    @IBOutlet weak var nextButton: UIButton!
    @IBOutlet weak var titleLable: UILabel!
    @IBOutlet weak var imageDescription: UILabel!
    //图片名称数组,
    lazy var imageArr:[NSDictionary] =
    {
        //获取 plist文件路径
        var filePath:String = (NSBundle.mainBundle().pathForResource("imageData", ofType: "plist"))!
        //从文件中读取配置信息
        var imageArr:NSArray! = NSArray(contentsOfFile: filePath)!
        //转换类型并返回
        return imageArr as! [NSDictionary]
    }()

    //当前显示图片的下标
    static var imageIndex = 0
    override func viewDidLoad() {
        super.viewDidLoad()

//        print(self.imageArr[0]["image"]!)
        updateImageView()
//        imageView.image = UIImage(imageLiteral: "2")
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //上一张图片
    @IBAction func preImage(sender: AnyObject) {
        ViewController.imageIndex--
        updateImageView()
    }
    //下一张图片
    @IBAction func nextImage(sender: AnyObject) {
        ViewController.imageIndex++
        updateImageView()
    }
    //更新页面
    func updateImageView()
    {
        //更新标题
        titleLable.text = "\(ViewController.imageIndex+1)/\(imageArr.count)"
        //设置上一页下一页按钮的状态
        preButton.enabled = ViewController.imageIndex != 0
        nextButton.enabled = ViewController.imageIndex < (imageArr.count - 1)
        //做个动画效果
        UIView.animateWithDuration(1, animations: {
            //
            if self.imageArr.count > ViewController.imageIndex
            {
                //设置 imageView 透明度,为了动画效果
                self.imageView.alpha = 0
                //设置 imageView 的图片
                self.imageView.image = UIImage(imageLiteral: self.imageArr[ViewController.imageIndex]["image"] as! String)
                //设置 当前图片的描述
                self.imageDescription.text = self.imageArr[ViewController.imageIndex]["description"] as? String
                self.imageView.alpha = 1
            }
        })
    }

}

按钮的基本使用以及控件的基本属性

//
//  ViewController.swift
//  按钮基本使用
//
//  Created by admin on 15/12/24.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageButton: UIButton!
    @IBOutlet var viewparent: UIView!
    @IBOutlet weak var lable: UILabel!
    @IBOutlet weak var viewA: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
//控件在相对于父控件左上角为坐标原点的位置坐标,类似 (32.0, 65.0, 139.0, 162.0),分别对应控件的 (横坐标,纵坐标,宽度,长度)
        print(lable.frame)
        //控件在相对于自己左上角为坐标原点的位置坐标,因为是相对于自己,所以横纵坐标为0,类似 (0.0, 0.0, 139.0, 162.0),分别对应控件的 (横坐标,纵坐标,宽度,长度)
        print(lable.bounds)
        //控件中点相对于父控件左上角为坐标原点的位置坐标,类似 (101.5, 146.0),分别对应控件的 (横坐标,纵坐标)
        print(lable.center)
        //控件的父控件,会是一个控件对象
        print(lable.superview)
        //控件的子对象,会是一个控件对象数组
        print(self.view.subviews)
        //控件的tag标示,父控件可以通过tag来找到对应的子控件
        print(lable.tag)
        //控件的旋转角度,比例缩放,平移等属性,类似 CGAffineTransform(a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0)
        print(lable.transform)
        //删除自己
//        viewA.removeFromSuperview()
        //添加一个控件
        viewA.addSubview(lable)
        //查找子控件中的tag值为指定值的控件
        print(viewparent.viewWithTag(3))
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //向上
    @IBAction func imageTop(sender: AnyObject) {
        imageButton.center.y -= 1
    }
    //向下
    @IBAction func imageButtom(sender: AnyObject) {
        imageButton.center.y += 1
    }
    //向右
    @IBAction func imageRight(sender: AnyObject) {
        imageButton.center.x -= 1
    }
    //向左
    @IBAction func imageLeft(sender: AnyObject) {
        imageButton.center.x += 1
    }
    //移动 x轴移动,y轴移动yua
    static var moveInt:CGFloat = 20
    @IBAction func moveImage(sender: AnyObject) {
        //这里如果写一个定值的话只在第一次点击的时候生效,所以需要借助一个变量
//        imageButton.transform = CGAffineTransformMakeTranslation(ViewController.moveInt, ViewController.moveInt)
//        ViewController.moveInt += 20
        //这里的平移是以第一个参数的基准进行偏移,不要额外的变量
        imageButton.transform = CGAffineTransformTranslate(imageButton.transform, 20, 20)
    }
    @IBAction func imageScale(sender: AnyObject) {
        //当这个值大于1的时候是方法,小于1的时候是缩小
        var scale:CGFloat = 0
        if sender.titleLabel!!.text! == "放大"
        {
            scale = 2
        }
        else if sender.titleLabel!!.text! == "缩小"
        {
            scale = 0.5
        }
        imageButton.transform = CGAffineTransformScale(imageButton.transform, scale, scale)
    }
    //旋转
    @IBAction func imageRotate(sender: AnyObject) {
        //animateWithDuration是实现动画效果,第一个参数是动画持续时间,第二个参数是一个闭包函数
        UIView.animateWithDuration(2.0, animations: {
            //这里的旋转单位是以圆周率为单位,这里是四分之一圆周率(45度)
            self.imageButton.transform = CGAffineTransformRotate(self.imageButton.transform, CGFloat(M_PI_4))
        })


    }
}


ios键盘的弹出与收回

1.弹出
这里以UITextField为例,其它控件应该也是一样的
选中控件,在右侧的属性面板(show the attributes inspector)找到Keyboard Type设置成自己想要的键盘形式
2.收回

//只有呼出键盘的对象才能收回键盘,所以这里调用了两次
        textFieldA.resignFirstResponder()
        textFieldB.resignFirstResponder()
//上面的例子只有两个设置了弹出键盘的控件,要是有很多的话可以用下面的代码,一句搞定
        self.view.endEditing(true)