[快速学会Swift第三方库] Eureka篇

前端之家收集整理的这篇文章主要介绍了[快速学会Swift第三方库] Eureka篇前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

[快速学会Swift第三方库] Eureka篇

Eureka可以帮你简单优雅的实现动态table-view表单。它由rows,sections和forms组成。如果你的app包含大量表单,Eureka可以真正帮你节省时间。

目录

编码之前

导入 Eureka

推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
手动安装:GitHub-Eureka主页

装好CocoaPods后,修改Podfile文件内容为如下:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios,'9.0'
use_frameworks!

target 'Web' do
pod 'Eureka','~> 1.6'
end
xcodeproj 'Desktop/Web/Web.xcodeproj'

target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

再执行命令:

$ pod install

其他操作

另外还需要在Target->工程名->Build Settings->Search Paths->User Header Search Paths处添加Eureka所在的目录:

最后在你需要用到Eureka的类中加上

import Eureka

创建表单

下面来创建一个最简单的表单,表单只包含一个区域和一行,点击该行可以切换到其它页面

import UIKit
import Eureka

//ViewController继承于FormViewController
class MyViewController: FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //表单form增加一个Section区域,区域名为First form
        form +++ Section("First form")

            //在区域中添加一个ButtonRow(ButtonRow为点击直接触发事件的行),行tag为Rows
            <<< ButtonRow("Rows"){
                //设置行标题为行tag
                $0.title = $0.tag
                //设置点击事件,执行名为"Main"的Segue(需在Interface Builder中自定义
                $0.presentationMode = .SegueName(segueName: "Main",completionCallback: nil)
        }
              //自定义Row,在后面会讲到
// <<< WeekDayRow(){
// $0.value = [.Monday,.Wednesday,.Friday]
// }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

效果如下图所示,与UITableview实现的界面大体一致,点击该行后会进入名为”Main”的Segue所指向的界面

基础表单

下面来创建一个包含标签,日期选择器,勾选,开关,滑动条,增减器等我们常用功能的表单。

//设置标签行的默认内容颜色为橙色
        LabelRow.defaultCellUpdate = { cell,row in cell.detailTextLabel?.textColor = .orangeColor() }
        //设置勾选行中勾颜色为橙色
        CheckRow.defaultCellUpdate = { cell,row in cell.tintColor = .orangeColor() }

        //为表单添加一个区域
        form +++ Section("Row examples")

            //为区域添加一个标签
            <<< LabelRow("LabelRow"){
                $0.title = $0.tag
                $0.value = "tap the row"
                }//选中标签行会在tittle后面加上" Summer "
                .onCellSelection{cell,row in
                    row.title = (row.title ?? "") + " Summer "
                    row.reload()
            }
            //为区域添加一个日期行。点击日期行会在屏幕底部弹出一个日期选择器
            <<< DateRow(){
                $0.value = NSDate()
                $0.title = "DateRow"
            }
            //为区域添加一个勾选行,默认为选中
            <<< CheckRow(){
                $0.title = "CheckRow"
                $0.value = true
            }
            //为区域添加一个开关行,默认为开
            <<< SwitchRow(){
                $0.title = "SwitchRow"
                $0.value = true
            }
            //为区域添加一个滑动条行,默认值为5
            <<< SliderRow(){
                $0.title = "SliderRow"
                $0.value = 5.0
            }
            //为区域添加一个增减器行,每次增减的大小为1
            <<< StepperRow(){
                $0.title = "StepperRow"
                $0.value = 1.0
        }

效果如下区域Row examples 中所示

点击DateRow弹出日期选择器效果

选择类型表单

Segment风格选择器

+++ Section("SegmentedRow examples")

            //只包含3个选择项
            <<< SegmentedRow<String>(){
                $0.options = ["One","Two","Three"]
            }
            //包含标题和3个选择项
            <<< SegmentedRow<String>(){
                $0.title = "Who are you?"
                $0.options = ["Summer","Seven","Leg","Cannon Fly","another one"]
                //默认选中"Leg"
                $0.value = "Leg"
            }
            //包含图片和3个选择项
            <<< SegmentedRow<String>(){
                $0.options = ["One","Three","Four"]
                $0.value = "Three"
                }.cellSetup{ cell,row in
                    cell.imageView?.image = UIImage(named: "sps.png")
        }

标准选择器

+++ Section("Selectors Rows Examples")

            //选择框以对话框的形式弹出
            <<< ActionSheetRow<String>(){
                $0.title = "ActionSheetRow"
                $0.selectorTitle = "Your favorite player?"
                $0.options = ["Diego Forlán","Edinson Cavani","Diego Lugano","Luis Suarez"]
                $0.value = "Luis Suarez"
            }
            //选择框以Alert的形式弹出
            <<< AlertRow<String>(){
                $0.title = "AlertRow"
                $0.selectorTitle = "Who is there"
                $0.options = ["Summer","another one"]
                $0.value = "Summer"
                //选中非当前值时打印新的值
                }.onChange{ (row) in
                    print(row.value)
                //选择框出现时,设置字体颜色为紫色
                }.onPresent({ (_,to) in
                    to.view.tintColor = .purpleColor()
                })
            //以navigation的形式进入到一个新界面,其中每行为选择内容
            <<< PushRow<String>(){
                $0.title = "PushRow"
                $0.options = ["Summer","another one"]
                $0.value = "Cannon Fly"
                $0.selectorTitle = "Choose an Emoji!"
        }

        //ipad特有的弹出框显示方式
        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            //获取section为当前表单最后一个区域
            let section = form.last!

            section <<< PopoverSelectorRow<String>(){
                $0.title = "PopoverSelectorRow"
                $0.options = ["Summer","another one"]
                $0.value = "Seven"
                $0.selectorTitle = "Choose an Emoji!"
            }
        }

        let section = form.last!

        section
            //图片选择器,点击从本地图片库选择
            <<< ImageRow(){
                $0.title = "ImageRow"
            }
            //多选器,以navigation的形式进入到一个新界面,其中每行为选择内容
            <<< MultipleSelectorRow<String>(){
                $0.title = "MultipleSelectorRow"
                $0.options = ["Summer","another one"]
                $0.value = ["Summer","Leg"]
                }
                .onPresent{ from,to in
                    to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done,target: from,action: #selector(ViewController.multipleSelectorDone(_:)))
            }

pickerView风格选择器

form +++ Section("Generic picker")

            //普通picker选择器
            <<< PickerRow<String>("PickerRow"){(row : PickerRow<String>) -> Void in
                row.options = []
                for i in 1...10{
                    row.options.append("opition\(i)")
                }
            }
            //内联picker选择器,可以通过点击展开或收起选择器
            <<< PickerInlineRow("Inline picker"){(row : PickerInlineRow<String>) -> Void in
                row.title = "Inline picker"
                row.options = []
                for i in 1...10{
                    row.options.append("opition\(i)")
                }
            }

三种风格选择器效果对比

由于博客上的编译器不支持上面截图中的图片型的字符串,所以以下都替换为普通字符串

PushRow效果展示:

PopoverSelectorRow效果展示:

带输入框的表单

+++ Section("FieldRow examples")
            //文本输入框
            <<< TextRow(){
                $0.title = "TextRow"
                $0.placeholder = "Placeholder"
            }
            //数字输入框
            <<< DecimalRow(){
                $0.title = "DecimalRow"
                $0.value = 5
                $0.formatter = DecimalFormatter()
                $0.useFormatterDuringInput = true
                //设置输入键盘为数字键盘
                }.cellSetup{cell,_ in
                    cell.textField.keyboardType = .NumberPad
            }
            //url输入框
            <<< URLRow(){
                $0.title = "URLRow"
                $0.value = NSURL(string: "http://blog.csdn.net/sps900608")
            }
            //电话输入框
            <<< PhoneRow() {
                $0.title = "PhoneRow (disabled)"
                $0.value = "+598 9898983510"
                $0.disabled = true
            }
            //姓名输入框
            <<< NameRow() {
                $0.title =  "NameRow"
            }
            //密码输入框
            <<< PasswordRow() {
                $0.title = "PasswordRow"
                $0.value = "password"
            }
            //整数输入框
            <<< IntRow() {
                $0.title = "IntRow"
                $0.value = 2016
            }
            //电子邮箱输入框
            <<< EmailRow() {
                $0.title = "EmailRow"
                $0.value = "scuxiatian@foxmail.com"
            }
            //推特地址输入框
            <<< TwitterRow() {
                $0.title = "TwitterRow"
                $0.value = "@xmartlabs"
            }
            //账户输入框
            <<< AccountRow() {
                $0.title = "AccountRow"
                $0.placeholder = "Placeholder"
            }
            //zip码输入框
            <<< ZipCodeRow{
                $0.title = "ZipCodeRow"
                $0.placeholder = "90210"
            }

            +++ Section("PostalAddressRow example")

            //邮政地址输入框
            <<< PostalAddressRow(){
                $0.title = "Address"
                $0.streetPlaceholder = "Street"
                $0.statePlaceholder = "State"
                $0.postalCodePlaceholder = "ZipCode"
                $0.cityPlaceholder = "City"
                $0.countryPlaceholder = "Country"

                //设置邮政地址的街道,邮编,城市,国家
                $0.value = PostalAddress(
                    street: "Dr. Mario Cassinoni 1011",state: nil,postalCode: "11200",city: "Montevideo",country: "Uruguay"
                )
        }

效果如下所示:

自定义Row

除了使用框架自带的Row,还可以根据自己的需求自定义Row,下面以一个星期选择行为例。首先创建类WeekDayRow.Swift和nib文件WeekDaysCell.xib。nib文件中只有一个TableViewCell,cell里并排有7个按钮分别对应周日~周一,按钮tittle为周日~周一英文的第一个字母,例如Monday对应的按钮,tittle为M。这个nib文件可以在GitHub上下载,也可以自己创建,另外需要用到选中和未选中的两张图片也都可以在GitHub上下载(选中时的图片未选中时的图片)或者用自己的,这里我用的是自己的。

import Foundation
import UIKit
import MapKit
import Eureka


//MARK: WeeklyDayCell

public enum WeekDay{
    case Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}

public class WeekDayCell : Cell<Set<WeekDay>>,CellType{

    //与nib中的7个按钮建立链接
    @IBOutlet var sundayButton: UIButton!
    @IBOutlet var mondayButton: UIButton!
    @IBOutlet var tuesdayButton: UIButton!
    @IBOutlet var wednesdayButton: UIButton!
    @IBOutlet var thursdayButton: UIButton!
    @IBOutlet var fridayButton: UIButton!
    @IBOutlet var saturdayButton: UIButton!

    //重写cell创建方法
    public override func setup() {
        height = {60}
        row.title = nil
        super.setup()
        selectionStyle = .None

        for subviews in contentView.subviews{
            if let button = subviews as? UIButton{
                //为每个按钮设置选中和未选中时的图片
                button.setImage(UIImage(named: "check.png"),forState: .Selected)
                button.setImage(UIImage(named: "uncheck.png"),forState: .Normal)
                //默认情况下,按钮在被禁用时,图像会被画的颜色淡一些,设置为false是禁止功能
                button.adjustsImageWhenDisabled = false
                //自定义函数,设置按钮标签图片的位置
                imageTopTittle(button)
            }
        }
    }

    //重写cell更新方法
    public override func update() {
        row.title = nil
        super.update()
        let value = row.value
        //根据value是否包含某枚举值来设置对应按钮的选中状态
        mondayButton.selected = value?.contains(.Monday) ?? false
        tuesdayButton.selected = value?.contains(.Tuesday) ?? false
        wednesdayButton.selected = value?.contains(.Wednesday) ?? false
        thursdayButton.selected = value?.contains(.Thursday) ?? false
        fridayButton.selected = value?.contains(.Friday) ?? false
        saturdayButton.selected = value?.contains(.Saturday) ?? false
        sundayButton.selected = value?.contains(.Sunday) ?? false

        //设置按钮在不同状态下的透明度
        mondayButton.alpha = row.isDisabled ? 0.6 : 1.0
        tuesdayButton.alpha = mondayButton.alpha
        wednesdayButton.alpha = mondayButton.alpha
        thursdayButton.alpha = mondayButton.alpha
        fridayButton.alpha = mondayButton.alpha
        saturdayButton.alpha = mondayButton.alpha
        sundayButton.alpha = mondayButton.alpha
    }

    //每个按钮的点击事件
    @IBAction func dayTapped(sender : UIButton){
        dayTapped(sender,day: getDayFromButton(sender))
    }

    //根据点击的按钮返回对应的枚举值
    private func getDayFromButton(button : UIButton) -> WeekDay{
        switch button{
        case sundayButton:
            return .Sunday
        case mondayButton:
            return .Monday
        case tuesdayButton:
            return .Tuesday
        case wednesdayButton:
            return .Wednesday
        case thursdayButton:
            return .Thursday
        case fridayButton:
            return .Friday
        default:
            return .Saturday
        }
    }

    //点击改变按钮的选中状态,并从value中插入或删除对应的枚举值
    private func dayTapped(button : UIButton,day:WeekDay){
        button.selected = !button.selected
        if button.selected {
            row.value?.insert(day)
        }
        else{
            row.value?.remove(day)
        }
    }

    //设置按钮标题图片的位置
    private func imageTopTittle(button : UIButton){
        guard let imageSize = button.imageView?.image?.size else{ return }
        let spacing : CGFloat = 3.0
        button.titleEdgeInsets = UIEdgeInsetsMake(0.0,-imageSize.width,-(imageSize.height + spacing),0.0)
        guard let titleLabel = button.titleLabel,let title = titleLabel.text else{ return }
        let titleSize = title.sizeWithAttributes([NSFontAttributeName: titleLabel.font])
        button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing),0,-titleSize.width)
    }
}

//MARK: WeekDayRow

public final class WeekDayRow: Row<Set<WeekDay>,WeekDayCell>,RowType{
    //重写init方法
    required public init(tag: String?) {
        super.init(tag: tag)
        displayValueFor = nil
        cellProvider = CellProvider<WeekDayCell>(nibName: "WeekDaysCell")
    }
}

完成之后就可以用与其他Row一样的方法来使用WeekDayRow了

<<< WeekDayRow(){
                $0.value = [.Monday,.Wednesday,.Friday]
        }

运行效果如图所示:

深入学习

这里列出了Eureka最基本的操作,Eureka还有更多丰富的功能,如果想要深入学习Eureka,可以前往GitHub-Eureka主页

原文链接:https://www.f2er.com/swift/323462.html

猜你在找的Swift相关文章