UI基础控件 Swift

//
// DefaultShowVC.swift
// Swift-UI
//
// Created by yangjun on 15/6/15.
// Copyright (c) 2015年 阳君. All rights reserved.
//

import UIKit

/** 样式*/
enum DefaultShowStyle : Int {
    case UILable
    case UIButton
    case UISegmentedControl
    case UITextField
    case UISlider
    case UISwitch
    case UIActivityIndicatorView
    case UIProgressView
    case UIPageControl
    case UIStepper
    case UIImageView
    case UITextView
    case UIDatePicker
    case UIPickerView
    case UIAlertView
    case UIActionSheet
}

/** 基础控件展示*/
class DefaultShowVC: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UIActionSheetDelegate {

    /** 样式*/
    var style: DefaultShowStyle = DefaultShowStyle.UILable;
    /** 屏幕宽*/
    private var width: CGFloat!
    /** 数据源*/
    private var dataArray: Array<Array<String>> = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.width = self.view.frame.size.width
        switch (self.style) {
        case DefaultShowStyle.UILable:
             self.initUILabel()
        case DefaultShowStyle.UIButton:
            self.initUIButton()
        case DefaultShowStyle.UISegmentedControl:
            self.initUISegmentedControl()
        case DefaultShowStyle.UITextField:
            self.initUITextField()
        case DefaultShowStyle.UISlider:
            self.initUISlider()
        case DefaultShowStyle.UISwitch:
            self.initUISwitch()
        case DefaultShowStyle.UIActivityIndicatorView:
            self.initUIActivityIndicatorView()
        case DefaultShowStyle.UIProgressView:
            self.initUIProgressView()
        case DefaultShowStyle.UIPageControl:
            self.initUIPageControl()
        case DefaultShowStyle.UIStepper:
            self.initUIStepper()
        case DefaultShowStyle.UIImageView:
            self.initUIImageView()
        case DefaultShowStyle.UITextView:
            self.initUITextView()
        case DefaultShowStyle.UIDatePicker:
            self.initUIDatePicker()
        case DefaultShowStyle.UIPickerView:
            self.initUIPickerView()
        case DefaultShowStyle.UIAlertView:
            self.initUIAlertView()
        case DefaultShowStyle.UIActionSheet:
            self.initUIActionSheet()
        default:
            println("未找到")
        }
    }

    // MARK: - UILable
    private func initUILabel() {
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, 110, 30))// 初始化
        label.backgroundColor = UIColor.clearColor()// 背景色
        label.font = UIFont.systemFontOfSize(17)// 字体大小
        label.textColor = UIColor.blueColor()// 字体颜色
        label.textAlignment = NSTextAlignment.Center// 居中
        label.text = self.title // 显示
        label.center = self.view.center// 居中显示
        self.view.addSubview(label)// 加载到当前view
    }

    // MARK: - UIButton
    private func initUIButton() {
        let button:UIButton = UIButton(frame: CGRectMake(0, 0, 30, 30))// 初始化
        button.addTarget(self, action: "buttonTouchUpInside:", forControlEvents: UIControlEvents.TouchUpInside)// 点击事件
        button.setImage(UIImage(named: "checked_un"), forState: UIControlState.Normal)// 默认
        button.setImage(UIImage(named: "checked"), forState: UIControlState.Selected)// 选中
        button.center = self.view.center// 居中显示
        self.view.addSubview(button)// 加载到当前view
    }

    // MARK: 用户点击UIButton
    func buttonTouchUpInside(button:UIButton) {
        button.selected = !button.selected
        self.title = "UIButton(\(button.selected))"
    }

    // MARK: - UISegmentedControl
    private func initUISegmentedControl() {
        let segmentedControl:UISegmentedControl = UISegmentedControl(items: ["1", "2", "3"])
        segmentedControl.frame = CGRectMake(0, 0, 200, 30);
        segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
        segmentedControl.selectedSegmentIndex = 0// 默认
        segmentedControl.center = self.view.center
        self.view.addSubview(segmentedControl)
    }

    // MARK: 用户点击UISegmentedControl
    func segmentedControlValueChanged(segmentedControl:UISegmentedControl) {
        self.title = "UISegmentedControl(\(segmentedControl.selectedSegmentIndex))"
    }

    // MARK: - UITextField
    private func initUITextField() {
        let textField:UITextField = UITextField(frame: CGRectMake(0, 0, 155, 30))
        textField.font = UIFont.systemFontOfSize(14)// 输入字体大小
        textField.delegate = self
        textField.keyboardType = UIKeyboardType.URL// 键盘样式
        textField.borderStyle = UITextBorderStyle.RoundedRect// 设置边框样式,只有设置了才会显示边框样式
        textField.clearButtonMode = UITextFieldViewMode.WhileEditing// 有一键删除按钮
        textField.center = self.view.center
        self.view.addSubview(textField)
        self.inputAccessoryView(textField)// 完成按钮放在键盘上方
    }

    // MARK: UITextFieldDelegate
    // MARK: 正要进入编辑状态
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        return true
    }

    // MARK: 实现监听返回按钮
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()// 关闭键盘
        return true
    }

    // MARK: 输入完毕
    func textFieldDidEndEditing(textField: UITextField) {
        self.title = "textField:\(textField.text)"
    }

    // MARK: - initUISlider
    private func initUISlider() {
        let slider: UISlider = UISlider(frame: CGRectMake(0, 0, 200, 31))
        slider.minimumValue = 0// 指定可变最小值
        slider.maximumValue = 100// 指定可变最大值
        slider.value = 50    // 指定初始值
        slider.addTarget(self, action: "sliderValueChanged:", forControlEvents: UIControlEvents.ValueChanged)// 响应事件
        slider.center = self.view.center
        self.view.addSubview(slider)
    }

    // MARK: 用户点击UISlider
    func sliderValueChanged(slider: UISlider) {
        self.title = "UISlider:\(slider.value)"
    }

    // MARK: - UISwitch
    private func initUISwitch() {
        let uiSwitch = UISwitch(frame: CGRectMake(0, 0, 51, 31))
        uiSwitch.tintColor = UIColor.blueColor()// 未打开时背景色
        uiSwitch.onTintColor = UIColor.greenColor()// 打开时背景色
        uiSwitch.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
        uiSwitch.center = self.view.center
        self.view.addSubview(uiSwitch)
    }

    // MARK: 用户点击UISwitch
    func switchValueChanged(uiSwitch: UISwitch) {
        self.title = "UISwitch:\(uiSwitch.on)"
    }

    // MARK: - UIActivityIndicatorView
    private func initUIActivityIndicatorView() {
        let activityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))//指定进度轮的大小
        activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge// 显示样式
        activityIndicatorView.backgroundColor = UIColor.greenColor()// 背景色
        activityIndicatorView.alpha = 0.5// 透明度
        //设置背景为圆角矩形
        activityIndicatorView.layer.cornerRadius = 6;
        activityIndicatorView.layer.masksToBounds = true;
        activityIndicatorView.startAnimating()// 开始
        activityIndicatorView.center = self.view.center
        self.view.addSubview(activityIndicatorView)
    }

    // MARK: - UIProgressView
    private func initUIProgressView() {
        let progressView = UIProgressView(frame: CGRectMake(0, 0, 150, 5))
        progressView.progressViewStyle = UIProgressViewStyle.Default// 进度条样式
        progressView.center = self.view.center
        self.view.addSubview(progressView)
        // 0.5秒触发一次
        let timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "changeNSTimer:", userInfo: progressView, repeats: true)
        timer.fire()// 启动
    }

    // MARK: - UIPageControl
    private func initUIPageControl() {
        let pageControl = UIPageControl(frame: CGRectMake(0, 0, 100, 37))
        pageControl.numberOfPages = 10// 默认10页
        pageControl.currentPage = 1// 选中第1页
        pageControl.pageIndicatorTintColor = UIColor.greenColor()// 默认背景色
        pageControl.currentPageIndicatorTintColor = UIColor.blueColor()// 选中时背景色
        pageControl.center = self.view.center
        self.view.addSubview(pageControl)
        // 0.5秒触发一次
        let timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "changeNSTimer:", userInfo: pageControl, repeats: true)
        timer.fire()// 启动
    }

    // MARK: - UIStepper
    private func initUIStepper() {
        let stepper = UIStepper(frame: CGRectMake(0, 0, 100, 50))
        stepper.maximumValue = 10// 最大
        stepper.minimumValue = 0// 最小
        stepper.value = 5// 默认
        stepper.stepValue = 0.1// 每次增加
        stepper.continuous = true// 按住不放来连续更改数值
        stepper.wraps = true// 是否循环(到最大值时再增加数值最从最小值开始)
        stepper.addTarget(self, action: "stepperValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
        stepper.center = self.view.center
        self.view.addSubview(stepper)
    }

    // MARK: 用户点击UIStepper
    func stepperValueChanged(stepper: UIStepper) {
        self.title = "UIStepper:\(stepper.value)"
    }

    // MARK: - UIImageView
    private func initUIImageView() {
        let image = UIImage(named: "tab_1")
        let imageView = UIImageView(image: image)
        println("\(imageView.frame)")
        imageView.center = self.view.center
        self.view.addSubview(imageView)
        self.view.backgroundColor = UIColor.lightGrayColor()
    }

    // MARK: - UITextView
    private func initUITextView() {
        let textView = UITextView(frame: CGRectMake(0, 0, self.width-30, 400), textContainer:nil)
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(14)
        textView.textAlignment = NSTextAlignment.Left// 对齐方式
        textView.layer.borderWidth = 1// 边宽
        textView.layer.borderColor = UIColor.lightGrayColor().CGColor// 边的颜色
        textView.layer.cornerRadius = 5// 圆角
        self.inputAccessoryView(textView)// 完成按钮放在键盘上方
        textView.center = self.view.center
        self.view.addSubview(textView)
    }

    // MARK: - UITextViewDelegate
    func textViewDidEndEditing(textView: UITextView) {
        println("UITextView: \(textView.text)")
    }

    // MARK: - UIDatePicker
    private func initUIDatePicker() {
        let datePicker = UIDatePicker(frame: CGRectMake(0, 0, self.width, 400))
        datePicker.datePickerMode = UIDatePickerMode.DateAndTime //设置样式,当前设为同时显示日期和时间
        datePicker.minuteInterval = 5// 设置分钟表盘的时间间隔(必须能让60整除,默认是1分钟)
        datePicker.date = NSDate()// 默认日期
        datePicker.addTarget(self, action: "datePickerValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
        // 设置日期范围(超过日期范围,会回滚到最近的有效日期)
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        datePicker.maximumDate = dateFormatter.dateFromString("2015-05-16 08:00:00")
        datePicker.minimumDate = dateFormatter.dateFromString("2015-07-16 08:00:00")
        // datePicker.setDate(NSDate(), animated: true)// 回到默认日期
        datePicker.center = self.view.center
        self.view.addSubview(datePicker)
    }

    // MARK: 用户选中UIDatePicker
    func datePickerValueChanged(datePicker: UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        self.title = "\(dateFormatter.stringFromDate(datePicker.date))"
    }

    // MARK: - UIPickerView
    private func initUIPickerView() {
        // 数据源
        self.dataArray.append(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
        self.dataArray.append(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
        let pickerView = UIPickerView(frame: CGRectMake(0, 0, self.width, 400))
        pickerView.dataSource = self
        pickerView.delegate = self
        pickerView.showsSelectionIndicator = true
        pickerView.center = self.view.center
        self.view.addSubview(pickerView)
    }

    // MARK: UIPickerViewDataSource
    // MARK: 列数
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {

        return self.dataArray.count
    }

    // MARK: 行数
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.dataArray[component].count
    }

    // MARK: UIPickerViewDelegate
    // MARK: 列宽
    func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return 40
    }

    // MARK: 行高
    func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 44
    }

    // MARK: 每行每列显示的数据
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        // 也可以实现func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView 二者取其一
        let array: Array = self.dataArray[component]
        return array[row]
    }

    // MARK: 用户选中UIPickerView
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        println("\(component)-\(row)")
        let first = self.dataArray[0][pickerView.selectedRowInComponent(0)]
        let second = self.dataArray[1][pickerView.selectedRowInComponent(1)]
        self.title = "UIPickerView:\(first)\(second)"
    }

    // MARK: - UIAlertView
    private func initUIAlertView() {
        let alertView = UIAlertView(title: "UIAlertView", message: "阳君测试", delegate: self, cancelButtonTitle: "取消")
        // 增加其他按钮
        alertView.addButtonWithTitle("1")
        alertView.addButtonWithTitle("2")
        alertView.show()// 显示
    }

    // MARK: UIAlertViewDelegate
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        // 判断是否点击取消按钮
        if (alertView.cancelButtonIndex == buttonIndex) {
            return
        }
        self.title = "UIAlertView:\(buttonIndex)"
    }

    // MARK: - UIActionSheet
    private func initUIActionSheet() {
        let actionSheet = UIActionSheet()
        actionSheet.title = "UIActionSheet"
        actionSheet.addButtonWithTitle("默认")// 添加按钮
        actionSheet.addButtonWithTitle("显著")// 添加显著按钮
        actionSheet.addButtonWithTitle("取消")// 添加取消按钮
        actionSheet.destructiveButtonIndex = 1// 显著按钮的位置
        actionSheet.cancelButtonIndex = actionSheet.numberOfButtons - 1// 取消按钮的位置
        actionSheet.delegate = self
        actionSheet.showInView(self.view.window)// 显示
    }

    // MARK: UIActionSheetDelegate
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        // 判断是否点击取消按钮
        if (actionSheet.cancelButtonIndex == buttonIndex) {
            return
        }
        self.title = "UIActionSheet:\(buttonIndex)"
    }

    // MARK: - 键盘上方添加确定按钮
    private func inputAccessoryView(view: UIView) {
        // 键盘上方的按钮
        let topView:UIToolbar = UIToolbar(frame: CGRectMake(0, 0, self.width, 30))
        let spaceButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)//定义两个flexibleSpace的button,放在toolBar上,这样完成按钮就会在最右边
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "onClickDone:")//定义完成按钮
        topView.items = [spaceButton, spaceButton, doneButton] //在toolBar上加上这些按钮

        // UITextView加确定按钮
        let textView:UITextView? = view as? UITextView
        textView?.inputAccessoryView = topView
        // UITextField加确定按钮
        let textField:UITextField? = view as? UITextField
        textField?.inputAccessoryView = topView
    }

    // 点击完成
    func onClickDone(button: UIBarButtonItem){
        self.view.endEditing(true)// 关闭键盘
    }

    // MARK: - 时间触发器
    func changeNSTimer(timer: NSTimer) {
        let progressView: UIProgressView? = timer.userInfo as? UIProgressView
        let pageControl: UIPageControl? = timer.userInfo as? UIPageControl
        if (progressView != nil) {
            var progress = progressView!.progress
            progress = progress == 1 ? 0 : progress + 0.01
            progressView!.progress = progress
            self.title =  NSString(format: "UIProgressView:%.2f", progress) as String
        } else if (pageControl != nil) {
            var currentPage = pageControl!.currentPage
            currentPage = currentPage == pageControl!.numberOfPages - 1 ? 0 : currentPage + 1
            pageControl!.currentPage = currentPage
            self.title = "UIProgressView:\(currentPage)"
        }
    }

}

你可能感兴趣的:(swift,控件)