repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
leavez/ComponentSwift
|
refs/heads/master
|
Example/CKWrapperDemo/DemoViewController.swift
|
mit
|
1
|
//
// DemoViewController.swift
// ComponentSwiftDemo
//
// Created by Gao on 18/06/2017.
// Copyright © 2017 leave. All rights reserved.
//
import Foundation
import ComponentSwift
class DemoViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
var datasource: CSCollectionViewDataSource!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.collectionView);
self.collectionView.frame = self.view.bounds
self.collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.collectionView.backgroundColor = .lightGray
self.datasource = CSCollectionViewDataSource(collectionView: collectionView, componentProvider: type(of: self), context: nil)
self.collectionView.delegate = self
self.collectionView.reloadData()
// add changeset
let changeset = ChangeSet().build {
$0.with(insertedSectionAt: 0)
$0.with(insertedItems: (0..<100).map{ ([0, $0], $0)})
}
self.datasource.apply(changeset, asynchronously: true)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.datasource.sizeForItem(at: indexPath)
}
}
extension DemoViewController: ComponentProviderProtocol {
static func csComponent(forModel model: Any, context: Any?) -> Component? {
guard let model = model as? Int else {
return nil
}
let allCount = 4
let component: Component?
switch model % allCount {
case 0:
component = DemoComponent(model: model)
case 1:
component = DemoComponent2()
case 2:
component = DemoComponent3()
case 3:
component = DemoComponent4()
default:
component = nil
}
return
CompositeComponent(
view:
ViewConfiguration(
attributes:
A.backgroundColor(.white)
),
component: component
)
}
}
|
1a2df77514fe08f34da3b4cc14ead1a1
| 28.576923 | 160 | 0.639792 | false | false | false | false |
joshua7v/ResearchOL-iOS
|
refs/heads/master
|
ResearchOL/Class/Me/Controller/ROLMeController.swift
|
mit
|
1
|
//
// ROLMeController.swift
// ResearchOL
//
// Created by Joshua on 15/4/11.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
class ROLMeController: SESettingViewController {
let storyboardIdForEdit = "ROLEditController"
var phoneNumber = SESettingLabelArrowItem()
var gender = SESettingLabelArrowItem()
var age = SESettingLabelArrowItem()
var hobby = SESettingLabelArrowItem()
var location = SESettingLabelArrowItem()
var income = SESettingLabelArrowItem()
var job = SESettingLabelArrowItem()
var edu = SESettingLabelArrowItem()
var marriage = SESettingLabelArrowItem()
var editController: ROLNavigationController {
get {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(self.storyboardIdForEdit) as! ROLNavigationController
}
}
@IBAction func logoutBtnDidClicked(sender: UIBarButtonItem) {
ROLUserInfoManager.sharedManager.resignUser()
}
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.tableView.registerNib(UINib(nibName: ROLCellIdentifiers.ROLMeProfileCell, bundle: nil), forCellReuseIdentifier: ROLCellIdentifiers.ROLMeProfileCell)
self.tableView.registerNib(UINib(nibName: ROLCellIdentifiers.ROLNeedToLoginCell, bundle: nil), forCellReuseIdentifier: ROLCellIdentifiers.ROLNeedToLoginCell)
}
// MARK: - setup
private func setup() {
// ROLUserInfoManager.sharedManager.isUserLogin
self.tableView.contentInsetTop = -44;
self.setupGroup0()
self.setupGroup1()
self.setupGroup2()
self.setupHeaderView()
}
// MARK: setup first group
private func setupGroup0() {
var group = self.addGroup()
var item = SESettingItem()
group.items = [item]
}
// MARK: setup second group
private func setupGroup1() {
var group = self.addGroup()
var phoneNumberText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kMobilePhoneNumberKey)
var phoneNumber = SESettingLabelArrowItem(icon: nil, title: "手机号", text: phoneNumberText == "" ? "未填写" : phoneNumberText, destVcClass: nil)
phoneNumber.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "手机号"
item.type = 2
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 0, inSection: 1)
})
}
var genderText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kGenderKey)
var gender = SESettingLabelArrowItem(icon: nil, title: "性别", text: genderText == "" ? "未填写" : genderText, destVcClass: nil)
gender.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "性别"
item.choices = ["男", "女"]
item.type = 1
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 1, inSection: 1)
})
}
var ageText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kAgeKey)
var age = SESettingLabelArrowItem(icon: nil, title: "年龄", text: ageText == "" ? "未填写" : ageText, destVcClass: nil)
age.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "年龄"
item.type = 2
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 2, inSection: 1)
})
}
var hobbyText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kHobbyKey)
var hobby = SESettingLabelArrowItem(icon: nil, title: "爱好", text: hobbyText == "" ? "未填写" : hobbyText, destVcClass: nil)
hobby.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "爱好"
item.choices = ["逛街", "游戏", "阅读", "旅行", "艺术"]
item.type = 1
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.isSingleChoice = false
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 3, inSection: 1)
})
}
var locationText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kLocationKey)
var location = SESettingLabelArrowItem(icon: nil, title: "地区", text: locationText == "" ? "未填写" : locationText, destVcClass: nil)
location.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "地区"
item.type = 2
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 4, inSection: 1)
})
}
group.items = [phoneNumber, gender, age, hobby, location]
self.phoneNumber = phoneNumber
self.gender = gender
self.age = age
self.hobby = hobby
self.location = location
}
private func setupGroup2() {
var group = self.addGroup()
var incomeText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kMonthlyIncomeKey)
var income = SESettingLabelArrowItem(icon: nil, title: "月收入", text: incomeText == "" ? "未填写" : incomeText, destVcClass: nil)
income.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "月收入"
item.choices = ["0 ~ 1999", "2000 ~ 3999", "4000 ~ 6999", "7000 ~ 9999", "10000 ~ 19999", "20000 以上"]
item.type = 1
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 0, inSection: 2)
})
}
var jobText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kJobStateIncomeKey)
var job = SESettingLabelArrowItem(icon: nil, title: "就业状态", text: jobText == "" ? "未填写" : jobText, destVcClass: nil)
job.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "就业状态"
item.choices = ["未参加工作", "工作中", "待业中", "已退休"]
item.type = 1
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 1, inSection: 2)
})
}
var eduText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kEducationStateKey)
var edu = SESettingLabelArrowItem(icon: nil, title: "教育程度", text: eduText == "" ? "未填写" : eduText, destVcClass: nil)
edu.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "教育程度"
item.choices = ["小学", "初中", "高中", "大学", "硕士", "博士"]
item.type = 1
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 2, inSection: 2)
})
}
var marriageText = ROLUserInfoManager.sharedManager.getAttributeForCurrentUser(ROLUserKeys.kMarriageStateKey)
var marriage = SESettingLabelArrowItem(icon: nil, title: "婚姻状况", text: marriageText == "" ? "未填写" : marriageText, destVcClass: nil)
marriage.operation = {
var item: ROLEditItem = ROLEditItem()
item.title = "婚姻状况"
item.choices = ["未婚", "已婚", "离异"]
item.type = 1
var editNavVC = self.editController
var editVC = editNavVC.viewControllers.first as! ROLEditController
editVC.item = item
editVC.delegate = self
self.presentViewController(editNavVC, animated: true, completion: { () -> Void in
editVC.indexPath = NSIndexPath(forRow: 3, inSection: 2)
})
}
group.items = [income, job, edu, marriage]
self.income = income
self.job = job
self.edu = edu
self.marriage = marriage
}
// MARK: setup headerView
private func setupHeaderView() {
}
}
extension ROLMeController: UITableViewDataSource {
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if ROLUserInfoManager.sharedManager.isUserLogin {
return super.numberOfSectionsInTableView(tableView)
} else {
return 1
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if ROLUserInfoManager.sharedManager.isUserLogin {
return super.tableView(tableView, numberOfRowsInSection: section)
} else {
return 1
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if ROLUserInfoManager.sharedManager.isUserLogin {
if (indexPath.section == 0) {
var cell: ROLMeProfileCell = tableView.dequeueReusableCellWithIdentifier(ROLCellIdentifiers.ROLMeProfileCell, forIndexPath: indexPath) as! ROLMeProfileCell
cell.item = AVUser.currentUser()
cell.delegate = self
return cell
} else {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
} else {
var cell = ROLNeedToLoginCell.cellWithTableView(tableView, indexPath: indexPath)
cell.delegate = self
return cell
}
}
}
extension ROLMeController: UITableViewDelegate {
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if ROLUserInfoManager.sharedManager.isUserLogin {
if (indexPath.section == 0) {
return ROLMeProfileCell.heightForProfileCell()
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
} else {
return ROLNeedToLoginCell.heightForNeedToLoginCel()
}
}
}
extension ROLMeController: ROLNeedToLoginCellDelegate {
func needToLoginCellLoginBtnDidClicked(cell: ROLNeedToLoginCell) {
self.presentViewController(UIStoryboard(name: "Login", bundle: nil).instantiateInitialViewController() as! UIViewController, animated: true, completion: nil)
}
}
extension ROLMeController: ROLMeProfileCellDelegate {
func meProfileCellAvatarDidClicked(cell: ROLMeProfileCell) {
var imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
// imagePicker.allowsEditing = false
imagePicker.delegate = self
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
extension ROLMeController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
NSNotificationCenter.defaultCenter().postNotificationName("AvatarDidChoseNotification", object: image, userInfo: nil)
var imageData = UIImageJPEGRepresentation(image, 0.5)
ROLUserInfoManager.sharedManager.saveAvatarForCurrentUser(imageData)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension ROLMeController: ROLEditControllerDelegate {
func editControllerSaveButtonDidClicked(editController: ROLEditController, item: ROLEditItem, value: String) {
self.setNewData(editController, item: item, value: value)
}
private func setNewData(editController: ROLEditController, item: ROLEditItem, value: String) {
if editController.indexPath.section == 1 {
switch editController.indexPath.row {
case 0:
self.phoneNumber.text = value
self.tableView.reloadData()
case 1:
self.gender.text = value
self.tableView.reloadData()
case 2:
self.age.text = value
self.tableView.reloadData()
case 3:
self.hobby.text = value
self.tableView.reloadData()
case 4:
self.location.text = value
self.tableView.reloadData()
default:
println("----default----")
}
} else if editController.indexPath.section == 2 {
switch editController.indexPath.row {
case 0:
self.income.text = value
self.tableView.reloadData()
case 1:
self.job.text = value
self.tableView.reloadData()
case 2:
self.edu.text = value
self.tableView.reloadData()
case 3:
self.marriage.text = value
self.tableView.reloadData()
default:
println("----default----")
}
}
}
}
|
dbeba8e345118b8dad96106cae30b6da
| 41.501416 | 171 | 0.619876 | false | false | false | false |
kunal732/MacLexa
|
refs/heads/master
|
HackathonAlexa/SimplePCMRecorder.swift
|
mit
|
1
|
//
// SimplePCMRecorder.swift
import Foundation
import Foundation
import CoreAudio
import AudioToolbox
struct RecorderState {
var setupComplete: Bool
var dataFormat: AudioStreamBasicDescription
var queue: UnsafeMutablePointer<AudioQueueRef>
var buffers: [AudioQueueBufferRef]
var recordFile: AudioFileID
var bufferByteSize: UInt32
var currentPacket: Int64
var isRunning: Bool
var recordPacket: Int64
var errorHandler: ((error:NSError) -> Void)?
}
class SimplePCMRecorder {
private var recorderState: RecorderState
init(numberBuffers:Int) {
self.recorderState = RecorderState(
setupComplete: false,
dataFormat: AudioStreamBasicDescription(),
queue: UnsafeMutablePointer<AudioQueueRef>.alloc(1),
buffers: Array<AudioQueueBufferRef>(count: numberBuffers, repeatedValue: nil),
recordFile:AudioFileID(),
bufferByteSize: 0,
currentPacket: 0,
isRunning: false,
recordPacket: 0,
errorHandler: nil)
}
deinit {
self.recorderState.queue.dealloc(1)
}
func setupForRecording(outputFileName:String, sampleRate:Float64, channels:UInt32, bitsPerChannel:UInt32, errorHandler: ((error:NSError) -> Void)?) throws {
self.recorderState.dataFormat.mFormatID = kAudioFormatLinearPCM
self.recorderState.dataFormat.mSampleRate = sampleRate
self.recorderState.dataFormat.mChannelsPerFrame = channels
self.recorderState.dataFormat.mBitsPerChannel = bitsPerChannel
self.recorderState.dataFormat.mFramesPerPacket = 1
self.recorderState.dataFormat.mBytesPerFrame = self.recorderState.dataFormat.mChannelsPerFrame * (self.recorderState.dataFormat.mBitsPerChannel / 8)
self.recorderState.dataFormat.mBytesPerPacket = self.recorderState.dataFormat.mBytesPerFrame * self.recorderState.dataFormat.mFramesPerPacket
self.recorderState.dataFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked
self.recorderState.errorHandler = errorHandler
try osReturningCall { AudioFileCreateWithURL(NSURL(fileURLWithPath: outputFileName), kAudioFileWAVEType, &self.recorderState.dataFormat, AudioFileFlags.DontPageAlignAudioData.union(.EraseFile), &self.recorderState.recordFile) }
self.recorderState.setupComplete = true
}
func startRecording() throws {
guard self.recorderState.setupComplete else { throw NSError(domain: Config.Error.ErrorDomain, code: Config.Error.PCMSetupIncompleteErrorCode, userInfo: [NSLocalizedDescriptionKey : "Setup needs to be called before starting"]) }
let osAQNI = AudioQueueNewInput(&self.recorderState.dataFormat, { (inUserData:UnsafeMutablePointer<Void>, inAQ:AudioQueueRef, inBuffer:AudioQueueBufferRef, inStartTime:UnsafePointer<AudioTimeStamp>, inNumPackets:UInt32, inPacketDesc:UnsafePointer<AudioStreamPacketDescription>) -> Void in
let internalRSP = unsafeBitCast(inUserData, UnsafeMutablePointer<RecorderState>.self)
if inNumPackets > 0 {
var packets = inNumPackets
let os = AudioFileWritePackets(internalRSP.memory.recordFile, false, inBuffer.memory.mAudioDataByteSize, inPacketDesc, internalRSP.memory.recordPacket, &packets, inBuffer.memory.mAudioData)
if os != 0 && internalRSP.memory.errorHandler != nil {
internalRSP.memory.errorHandler!(error:NSError(domain: NSOSStatusErrorDomain, code: Int(os), userInfo: nil))
}
internalRSP.memory.recordPacket += Int64(packets)
}
if internalRSP.memory.isRunning {
let os = AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, nil)
if os != 0 && internalRSP.memory.errorHandler != nil {
internalRSP.memory.errorHandler!(error:NSError(domain: NSOSStatusErrorDomain, code: Int(os), userInfo: nil))
}
}
}, &self.recorderState, nil, nil, 0, self.recorderState.queue)
guard osAQNI == 0 else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(osAQNI), userInfo: nil) }
let bufferByteSize = try self.computeRecordBufferSize(self.recorderState.dataFormat, seconds: 0.5)
for (var i = 0; i < self.recorderState.buffers.count; ++i) {
try osReturningCall { AudioQueueAllocateBuffer(self.recorderState.queue.memory, UInt32(bufferByteSize), &self.recorderState.buffers[i]) }
try osReturningCall { AudioQueueEnqueueBuffer(self.recorderState.queue.memory, self.recorderState.buffers[i], 0, nil) }
}
try osReturningCall { AudioQueueStart(self.recorderState.queue.memory, nil) }
self.recorderState.isRunning = true
}
func stopRecording() throws {
self.recorderState.isRunning = false
try osReturningCall { AudioQueueStop(self.recorderState.queue.memory, true) }
try osReturningCall { AudioQueueDispose(self.recorderState.queue.memory, true) }
try osReturningCall { AudioFileClose(self.recorderState.recordFile) }
}
private func computeRecordBufferSize(format:AudioStreamBasicDescription, seconds:Double) throws -> Int {
let framesNeededForBufferTime = Int(ceil(seconds * format.mSampleRate))
if format.mBytesPerFrame > 0 {
return framesNeededForBufferTime * Int(format.mBytesPerFrame)
} else {
var maxPacketSize = UInt32(0)
if format.mBytesPerPacket > 0 {
maxPacketSize = format.mBytesPerPacket
} else {
try self.getAudioQueueProperty(kAudioQueueProperty_MaximumOutputPacketSize, value: &maxPacketSize)
}
var packets = 0
if format.mFramesPerPacket > 0 {
packets = framesNeededForBufferTime / Int(format.mFramesPerPacket)
} else {
packets = framesNeededForBufferTime
}
if packets == 0 {
packets = 1
}
return packets * Int(maxPacketSize)
}
}
private func osReturningCall(osCall: () -> OSStatus) throws {
let os = osCall()
if os != 0 {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(os), userInfo: nil)
}
}
private func getAudioQueueProperty<T>(propertyId:AudioQueuePropertyID, inout value:T) throws {
let propertySize = UnsafeMutablePointer<UInt32>.alloc(1)
propertySize.memory = UInt32(sizeof(T))
let os = AudioQueueGetProperty(self.recorderState.queue.memory,
propertyId,
&value,
propertySize)
propertySize.dealloc(1)
guard os == 0 else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(os), userInfo: nil) }
}
}
|
70df7b8c26111f7268fe788fea073472
| 42.89759 | 296 | 0.645484 | false | false | false | false |
ifLab/WeCenterMobile-iOS
|
refs/heads/master
|
WeCenterMobile/Controller/MainViewController.swift
|
gpl-2.0
|
1
|
//
// MainViewController.swift
// WeCenterMobile
//
// Created by Darren Liu on 14/7/26.
// Copyright (c) 2014年 ifLab. All rights reserved.
//
import GBDeviceInfo
import UIKit
let SidebarDidBecomeVisibleNotificationName = "SidebarDidBecomeVisibleNotification"
let SidebarDidBecomeInvisibleNotificationName = "SidebarDidBecomeInvisibleNotification"
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MSRSidebarDelegate, UserEditViewControllerDelegate {
lazy var contentViewController: MSRNavigationController = {
[weak self] in
let vc = MSRNavigationController(rootViewController: HomeViewController(user: User.currentUser!))
let theme = SettingsManager.defaultManager.currentTheme
vc.view.backgroundColor = theme.backgroundColorA
vc.backButtonImage = UIImage(named: "Navigation-Back")
return vc
}()
lazy var sidebar: MSRSidebar = {
[weak self] in
let display = GBDeviceInfo.deviceInfo().display
let widths: [GBDeviceDisplay: CGFloat] = [
.DisplayUnknown: 300,
.DisplayiPad: 300,
.DisplayiPhone35Inch: 220,
.DisplayiPhone4Inch: 220,
.DisplayiPhone47Inch: 260,
.DisplayiPhone55Inch: 300]
let v = MSRSidebar(width: widths[display]!, edge: .Left)
v.animationDuration = 0.3
v.enableBouncing = false
v.overlay = UIView()
v.overlay!.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
v.delegate = self
if let self_ = self {
v.contentView.addSubview(self_.tableView)
self_.tableView.msr_addAllEdgeAttachedConstraintsToSuperview()
}
return v
}()
lazy var tableView: UITableView = {
[weak self] in
let v = UITableView(frame: CGRectZero, style: .Plain)
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.clearColor()
v.separatorColor = UIColor.clearColor()
v.delegate = self
v.dataSource = self
v.separatorStyle = .None
v.showsVerticalScrollIndicator = true
v.delaysContentTouches = false
v.msr_wrapperView?.delaysContentTouches = false
if let self_ = self {
v.addSubview(self_.userView)
v.contentInset.top = self_.userView.minHeight
}
return v
}()
lazy var userView: SidebarUserView = {
[weak self] in
let v = NSBundle.mainBundle().loadNibNamed("SidebarUserView", owner: nil, options: nil).first as! SidebarUserView
v.update(user: User.currentUser)
if let self_ = self {
let tgr = UITapGestureRecognizer(target: self_, action: "didTapSignatureLabel:")
v.overlay.addGestureRecognizer(tgr)
}
return v
}()
lazy var cells: [SidebarCategoryCell] = {
[weak self] in
if let self_ = self {
return SidebarCategory.allValues.map {
let cell = NSBundle.mainBundle().loadNibNamed("SidebarCategoryCell", owner: nil, options: nil).first as! SidebarCategoryCell
cell.update(category: $0)
return cell
}
} else {
return []
}
}()
lazy var logoutCell: SidebarLogoutCell = {
[weak self] in
let cell = NSBundle.mainBundle().loadNibNamed("SidebarLogoutCell", owner: nil, options: nil).first as! SidebarLogoutCell
return cell
}()
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override func loadView() {
super.loadView()
contentViewController.interactivePopGestureRecognizer.requireGestureRecognizerToFail(sidebar.screenEdgePanGestureRecognizer)
addChildViewController(contentViewController)
view.addSubview(contentViewController.view)
view.insertSubview(sidebar, aboveSubview: contentViewController.view)
let theme = SettingsManager.defaultManager.currentTheme
sidebar.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: theme.backgroundBlurEffectStyle))
automaticallyAdjustsScrollViewInsets = false
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.selectRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0), animated: false, scrollPosition: .None)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "currentUserPropertyDidChange:", name: CurrentUserPropertyDidChangeNotificationName, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "currentThemeDidChange", name: CurrentThemeDidChangeNotificationName, object: nil)
}
var firstAppear = true
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if firstAppear {
firstAppear = false
tableView.contentOffset.y = -tableView.contentInset.top
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return [cells.count, 1][section]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 0 {
let c = cells[indexPath.row]
c.updateTheme()
cell = c
} else {
cell = logoutCell
}
return cell
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if tableView.indexPathForSelectedRow == indexPath {
return nil
}
let cell = tableView.cellForRowAtIndexPath(indexPath)
if let category = (cell as? SidebarCategoryCell)?.category {
if category == .Publishment {
let ac = UIAlertController(title: "发布什么?", message: "选择发布的内容种类。", preferredStyle: .ActionSheet)
let presentPublishmentViewController: (String, PublishmentViewControllerPresentable) -> Void = {
[weak self] title, object in
let vc = NSBundle.mainBundle().loadNibNamed("PublishmentViewControllerA", owner: nil, options: nil).first as! PublishmentViewController
vc.dataObject = object
vc.headerLabel.text = title
self?.presentViewController(vc, animated: true, completion: nil)
self?.sidebar.collapse()
}
ac.addAction(UIAlertAction(title: "问题", style: .Default) {
action in
presentPublishmentViewController("发布问题", Question.temporaryObject())
})
ac.addAction(UIAlertAction(title: "文章", style: .Default) {
action in
presentPublishmentViewController("发布文章", Article.temporaryObject())
})
ac.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil))
presentViewController(ac, animated: true, completion: nil)
return nil
}
}
return indexPath
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
sidebar.collapse()
let cell = tableView.cellForRowAtIndexPath(indexPath)
if let category = (cell as? SidebarCategoryCell)?.category {
switch category {
case .User:
contentViewController.setViewControllers([UserViewController(user: User.currentUser!)], animated: true)
break
case .Home:
contentViewController.setViewControllers([HomeViewController(user: User.currentUser!)], animated: true)
break
case .Explore:
contentViewController.setViewControllers([ExploreViewController()], animated: true)
break
case .Search:
contentViewController.setViewControllers([SearchViewController()], animated: true)
break
case .Topic:
contentViewController.setViewControllers([HotTopicViewController()], animated: true)
break
case .Settings:
let svc = UIStoryboard(name: "SettingsViewController", bundle: NSBundle.mainBundle()).instantiateInitialViewController() as! SettingsViewController
contentViewController.setViewControllers([svc], animated: true)
break
default:
break
}
} else if cell is SidebarLogoutCell {
dismissViewControllerAnimated(true, completion: nil)
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return [50, 50][indexPath.section]
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView()
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return [0, 10][section]
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
let inset = scrollView.contentInset.top
userView.frame = CGRect(x: 0, y: min(-inset, offset), width: scrollView.bounds.width, height: userView.minHeight + max(0, -(offset + inset)))
scrollView.scrollIndicatorInsets.top = max(0, -offset)
}
func msr_sidebarDidCollapse(sidebar: MSRSidebar) {
setNeedsStatusBarAppearanceUpdate()
}
func msr_sidebarDidExpand(sidebar: MSRSidebar) {
setNeedsStatusBarAppearanceUpdate()
}
var sidebarIsVisible: Bool = false {
didSet {
if sidebarIsVisible != oldValue {
NSNotificationCenter.defaultCenter().postNotificationName(sidebarIsVisible ? SidebarDidBecomeVisibleNotificationName : SidebarDidBecomeInvisibleNotificationName, object: sidebar)
}
}
}
func msr_sidebar(sidebar: MSRSidebar, didShowAtPercentage percentage: CGFloat) {
sidebarIsVisible = percentage > 0
}
func didTapSignatureLabel(recognizer: UITapGestureRecognizer) {
if recognizer.state == .Ended {
sidebar.collapse()
let uevc = NSBundle.mainBundle().loadNibNamed("UserEditViewController", owner: nil, options: nil).first as! UserEditViewController
uevc.delegate = self
showDetailViewController(uevc, sender: self)
}
}
func currentUserPropertyDidChange(notification: NSNotification) {
let key = notification.userInfo![KeyUserInfoKey] as! String
if key == "avatarData" || key == "name" || key == "signature" {
userView.update(user: User.currentUser)
}
}
func currentThemeDidChange() {
let theme = SettingsManager.defaultManager.currentTheme
sidebar.backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: theme.backgroundBlurEffectStyle))
let indexPath = tableView.indexPathForSelectedRow
tableView.reloadData()
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return sidebar.collapsed ? contentViewController.preferredStatusBarStyle() : .LightContent
}
override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
return .Slide
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
ff0ee7ff45829de2186ed571f59f3733
| 44.29845 | 194 | 0.650723 | false | false | false | false |
lukaskollmer/RuntimeKit
|
refs/heads/master
|
RuntimeKit/Sources/Protocols.swift
|
mit
|
1
|
//
// Protocols.swift
// RuntimeKit
//
// Created by Lukas Kollmer on 31.03.17.
// Copyright © 2017 Lukas Kollmer. All rights reserved.
//
import Foundation
import ObjectiveC
/// struct describing a method for a protocol
public struct ObjCMethodDescription {
/// The method's name
let name: Selector
/// The method's return type
let returnType: ObjCTypeEncoding
/// The method's argument types
let argumentTypes: [ObjCTypeEncoding]
/// `MethodType` case determining whether the method is an instance method or a class method
let methodType: MethodType
/// Boolean determining whether the method is required
var isRequired = false
/// The method's encoding
var encoding: [CChar] {
return TypeEncoding(returnType, argumentTypes)
}
/// Create a new `ObjCMethodDescription` instance
///
/// - Parameters:
/// - name: The method's name
/// - returnType: The method's return type
/// - argumentTypes: The method's argument types
/// - methodType: `MethodType` case determining whether the method is an instance method or a class method
/// - isRequired: Boolean determining whether the method is required
init(_ name: Selector, returnType: ObjCTypeEncoding = .void, argumentTypes: [ObjCTypeEncoding] = [.object, .selector], methodType: MethodType, isRequired: Bool = false) {
self.name = name
self.returnType = returnType
self.argumentTypes = argumentTypes
self.methodType = methodType
}
}
public extension Runtime {
/// Returns a specified protocol
///
/// - Parameter name: The name of a protocol.
/// - Returns: The protocol named `name`, or `nil` if no protocol named name could be found
public static func getProtocol(_ name: String) -> Protocol? {
return objc_getProtocol(name.cString(using: .utf8)!)
}
/// Creates a new protocol instance.
///
/// - Parameters:
/// - name: The name of the protocol you want to create.
/// - methods: The methods you want to add to the new protocol
/// - Returns: A new protocol instance
/// - Throws: `RuntimeKitError.protocolAlreadyExists` if a protocol with the same name already exists, `RuntimeKitError.unableToCreateProtocol` if there was an error creating the protocol
public static func createProtocol(_ name: String, methods: [ObjCMethodDescription]) throws -> Protocol {
guard Runtime.getProtocol(name) == nil else {
throw RuntimeKitError.protocolAlreadyExists
}
guard let newProtocol = objc_allocateProtocol(name.cString(using: .utf8)!) else {
throw RuntimeKitError.unableToCreateProtocol
}
methods.forEach {
protocol_addMethodDescription(newProtocol, $0.name, $0.encoding, $0.isRequired, $0.methodType == .instance)
}
objc_registerProtocol(newProtocol)
return newProtocol
}
}
|
4ab91f50a95dba9f939adf1faf939925
| 35.301205 | 191 | 0.659476 | false | false | false | false |
coodly/laughing-adventure
|
refs/heads/master
|
Source/Feedback/ComposeViewController.swift
|
apache-2.0
|
1
|
/*
* Copyright 2016 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
#if os(iOS)
private extension Selector {
static let sendPressed = #selector(ComposeViewController.sendPressed)
static let cancelPressed = #selector(ComposeViewController.cancelPressed)
static let keyboardChanged = #selector(ComposeViewController.keyboardChanged(notification:))
}
internal class ComposeViewController: UIViewController {
var entryHandler: ((String) -> ())!
private var bottomSpacing: NSLayoutConstraint!
private var textView: UITextView!
override func viewDidLoad() {
navigationItem.title = NSLocalizedString("coodly.feedback.message.compose.controller.title", comment: "")
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: .cancelPressed)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("coodly.feedback.message.compose.controller.send.button", comment: ""), style: .plain, target: self, action: .sendPressed)
textView = UITextView(frame: view.bounds)
textView.font = UIFont.preferredFont(forTextStyle: .body)
view.addSubview(textView)
let views: [String: AnyObject] = ["text": textView]
textView.translatesAutoresizingMaskIntoConstraints = false
let vertical = NSLayoutConstraint.constraints(withVisualFormat: "V:|[text]-(123)-|", options: [], metrics: nil, views: views)
let horizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|[text]|", options: [], metrics: nil, views: views)
view.addConstraints(vertical + horizontal)
for c in view.constraints {
if c.constant == 123 {
bottomSpacing = c
break
}
}
bottomSpacing.constant = 0
NotificationCenter.default.addObserver(self, selector: .keyboardChanged, name: Notification.Name.UIKeyboardDidChangeFrame, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.becomeFirstResponder()
}
@objc fileprivate func sendPressed() {
guard let message = textView.text, message.hasValue() else {
return
}
entryHandler(message)
}
@objc fileprivate func cancelPressed() {
dismiss(animated: true, completion: nil)
}
@objc fileprivate func keyboardChanged(notification: Notification) {
guard let info = notification.userInfo, let end = info[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyWindow = UIApplication.shared.keyWindow!
let meInScreen = keyWindow.convert(view.frame, from: view)
let frame = end.cgRectValue
let keyboardInScreen = keyWindow.convert(frame, from: keyWindow.rootViewController!.view)
let intersection = meInScreen.intersection(keyboardInScreen)
bottomSpacing.constant = intersection.height
}
}
#endif
|
d5dac3355afd0c5414d517d2d73439b6
| 38.129032 | 207 | 0.681506 | false | false | false | false |
richardpiazza/XCServerAPI
|
refs/heads/master
|
Example/Pods/CodeQuickKit/Sources/Ubiquity.swift
|
mit
|
2
|
#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS))
import Foundation
public enum UbiquityState {
case disabled
case deviceOnly
case available
public var description: String {
switch self {
case .disabled: return "Disabled"
case .deviceOnly: return "Device Only"
case .available: return "Available"
}
}
public var longDescription: String {
switch self {
case .disabled: return "iCloud is not enabled on this device."
case .deviceOnly: return "iCloud is enabled, but the application container does not exist."
case .available: return "iCloud is enabled, and the application container is ready."
}
}
}
public enum UbiquityError: Error {
case invalidState
public var localizedDescription: String {
return "Invalid Ubiquity State: This application does not have access to a valid iCloud ubiquity container."
}
}
public protocol UbiquityContainerDelegate {
func ubiquityStateDidChange(_ oldState: UbiquityState, newState: UbiquityState)
}
open class UbiquityContainer: UbiquityContainerDelegate {
public static let defaultContainer: UbiquityContainer = UbiquityContainer()
public internal(set) var identifier: String?
public internal(set) var directory: URL?
public internal(set) var ubiquityIdentityToken = FileManager.default.ubiquityIdentityToken
public var delegate: UbiquityContainerDelegate?
public var ubiquityState: UbiquityState {
guard let _ = ubiquityIdentityToken else {
return .disabled
}
guard let _ = directory else {
return .deviceOnly
}
return .available
}
public init(identifier: String? = nil, delegate: UbiquityContainerDelegate? = nil) {
self.identifier = identifier
self.delegate = delegate != nil ? delegate : self
NotificationCenter.default.addObserver(self, selector: #selector(UbiquityContainer.ubiquityIdentityDidChange(_:)), name: NSNotification.Name.NSUbiquityIdentityDidChange, object: nil)
let oldState = ubiquityState
DispatchQueue.global(qos: .default).async {
self.directory = FileManager.default.url(forUbiquityContainerIdentifier: identifier)
let newState = self.ubiquityState
if let delegate = self.delegate {
DispatchQueue.main.async(execute: {
delegate.ubiquityStateDidChange(oldState, newState: newState)
})
}
}
}
@objc fileprivate func ubiquityIdentityDidChange(_ notification: Notification) {
let oldState = ubiquityState
self.ubiquityIdentityToken = FileManager.default.ubiquityIdentityToken
let newState = ubiquityState
if let delegate = self.delegate {
delegate.ubiquityStateDidChange(oldState, newState: newState)
}
}
public func ubiquityStateDidChange(_ oldState: UbiquityState, newState: UbiquityState) {
Log.debug("Ubiquity State did change from '\(oldState.description)' to '\(newState.description)'")
}
}
#endif
|
b33c7406c32650272b275b9b353f72dd
| 33.361702 | 190 | 0.659443 | false | false | false | false |
Instagram/IGListKit
|
refs/heads/main
|
Source/IGListSwiftKit/IGListCollectionContext+Refinements.swift
|
mit
|
1
|
/*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import IGListKit
import UIKit
extension ListCollectionContext {
/**
Dequeues a cell from the collection view reuse pool.
- Parameters:
- reuseIdentifier: A reuse identifier for the specified cell. This parameter may be `nil`.
- sectionController: The section controller requesting this information.
- index: The index of the cell.
- Returns: A cell dequeued from the reuse pool or a newly created one.
*/
public func dequeueReusableCell<T: UICollectionViewCell>(
withReuseIdentifier reuseIdentifier: String,
for sectionController: ListSectionController,
at index: Int
) -> T {
guard let cell = self.dequeueReusableCell(
of: T.self,
withReuseIdentifier: reuseIdentifier,
for: sectionController,
at: index
) as? T else {
fatalError()
}
return cell
}
/**
Dequeues a cell from the collection view reuse pool.
- Parameters:
- sectionController: The section controller requesting this information.
- index: The index of the cell.
- Returns: A cell dequeued from the reuse pool or a newly created one.
- Note: This method uses a string representation of the cell class as the identifier.
*/
public func dequeueReusableCell<T: UICollectionViewCell>(
for sectionController: ListSectionController,
at index: Int
) -> T {
guard let cell = self.dequeueReusableCell(
of: T.self,
for: sectionController,
at: index
) as? T else {
fatalError()
}
return cell
}
/**
Dequeues a cell from the collection view reuse pool.
- Parameters:
- nibName: The name of the nib file.
- bundle: The bundle in which to search for the nib file. If `nil`, this method searches the main bundle.
- sectionController: The section controller requesting this information.
- index: The index of the cell.
- Returns: A cell dequeued from the reuse pool or a newly created one.
- Note: This method uses the nib name as the reuse identifier.
*/
public func dequeueReusableCell<T: UICollectionViewCell>(
withNibName nibName: String,
bundle: Bundle?,
for sectionController: ListSectionController,
at index: Int
) -> T {
guard let cell = self.dequeueReusableCell(
withNibName: nibName,
bundle: bundle,
for: sectionController,
at: index
) as? T else {
fatalError("A nib named \"\(nibName)\" was not found in \(String(describing:bundle))")
}
return cell
}
/**
Dequeues a storyboard prototype cell from the collection view reuse pool.
- Parameters:
- identifier: The identifier of the cell prototype in storyboard.
- sectionController: The section controller requesting this information.
- index: The index of the cell.
- Returns: A cell dequeued from the reuse pool or a newly created one.
*/
public func dequeueReusableCellFromStoryboard<T: UICollectionViewCell>(
withIdentifier reuseIdentifier: String,
for sectionController: ListSectionController,
at index: Int
) -> T {
guard let cell = self.dequeueReusableCellFromStoryboard(
withIdentifier: reuseIdentifier,
for: sectionController,
at: index
) as? T else {
fatalError("A cell with the identifier \"\(reuseIdentifier)\" was not found in the storyboard")
}
return cell
}
/**
Dequeues a supplementary view from the collection view reuse pool.
- Parameters:
- elementKind: The kind of supplementary view.
- sectionController: The section controller requesting this information.
- index: The index of the supplementary view.
- Returns: A supplementary view dequeued from the reuse pool or a newly created one.
- Note: This method uses a string representation of the view class and the kind as the identifier.
*/
public func dequeueReusableSupplementaryView<T: UICollectionReusableView>(
ofKind elementKind: String,
forSectionController sectionController: ListSectionController,
atIndex index: NSInteger
) -> T {
guard let supplementaryView = self.dequeueReusableSupplementaryView(
ofKind: elementKind,
for: sectionController,
class: T.self,
at: index
) as? T else {
fatalError()
}
return supplementaryView
}
/**
Dequeues a supplementary view from the collection view reuse pool.
- Parameters:
- elementKind: The kind of supplementary view.
- identifier: The identifier of the supplementary view in storyboard.
- sectionController: The section controller requesting this information.
- index: The index of the supplementary view.
- Returns: A supplementary view dequeued from the reuse pool or a newly created one.
*/
public func dequeueReusableSupplementaryViewFromStoryboard<T: UICollectionReusableView>(
ofKind elementKind: String,
withIdentifier identifier: String,
forSectionController sectionController: ListSectionController,
atIndex index: Int
) -> T {
guard let supplementaryView = self.dequeueReusableSupplementaryView(
fromStoryboardOfKind: elementKind,
withIdentifier: identifier,
for: sectionController,
at: index
) as? T else {
fatalError()
}
return supplementaryView
}
/**
Dequeues a supplementary view from the collection view reuse pool.
- Parameters:
- elementKind: The kind of supplementary view.
- sectionController: The section controller requesting this information.
- nibName: The name of the nib file.
- bundle: The bundle in which to search for the nib file. If `nil`, this method searches the main bundle.
- index: The index of the supplementary view.
- Returns: A supplementary view dequeued from the reuse pool or a newly created one.
- Note: This method uses the nib name as the reuse identifier.
*/
public func dequeueReusableSupplementaryView<T: UICollectionReusableView>(
ofKind elementKind: String,
forSectionController sectionController: ListSectionController,
nibName: String,
bundle: Bundle?,
atIndex index: Int
) -> T {
guard let supplementaryView = self.dequeueReusableSupplementaryView(
ofKind: elementKind,
for: sectionController,
nibName: nibName,
bundle: bundle,
at: index
) as? T else {
fatalError()
}
return supplementaryView
}
}
|
21777c1c1bd4a9e76d5dab3d5d08a8d1
| 32.924883 | 114 | 0.638251 | false | false | false | false |
cliqz-oss/browser-ios
|
refs/heads/development
|
Client/Cliqz/Frontend/Browser/CustomViews/LogoPlaceholder.swift
|
mpl-2.0
|
2
|
//
// LogoPlaceholder.swift
// Client
//
// Created by Sahakyan on 7/3/17.
// Copyright © 2017 Mozilla. All rights reserved.
//
import Foundation
import SnapKit
class LogoPlaceholder: UIView {
init(logoInfo: LogoInfo) {
super.init(frame: CGRect.zero)
if let color = logoInfo.color {
self.backgroundColor = UIColor(colorString: color)
} else {
self.backgroundColor = UIColor.black
}
let l = UILabel()
l.textColor = UIColor.white
if let title = logoInfo.prefix {
l.text = title
} else {
l.text = "N/A"
}
let fontSize = logoInfo.fontSize ?? 15
l.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
self.addSubview(l)
l.snp.makeConstraints({ (make) in
make.center.equalTo(self)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
da971b841bc251a2be7bc5b7c8ecfcf5
| 20.384615 | 55 | 0.679856 | false | false | false | false |
AleksanderKoko/WikimediaCommonsApi
|
refs/heads/master
|
Example/WCApi/VideosTableViewController.swift
|
mit
|
1
|
import Foundation
import UIKit
import WCApi
class VideosTableViewController: UITableViewController, GetMultimediaHandlerProtocol {
var multimedia: [MultimediaModel] = [MultimediaModel]()
override func viewDidLoad() {
super.viewDidLoad()
let getMultimedia = GetMultimedia(handler: self)
let user: UserModel = UserModel(username: "Harish_satpute")
getMultimedia.get(user)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.multimedia.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("video", forIndexPath: indexPath)
let multimedia = self.multimedia[indexPath.row] as MultimediaModel
cell.textLabel?.text = multimedia.name
return cell
}
/*
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension VideosTableViewController{
func setMultimedia(multimedia: [MultimediaModel]){
self.multimedia = multimedia.filter(){
if $0.mediaType == MultimediaModel.MediaTypes.video {
return true
} else {
return false
}
}
self.tableView.reloadData()
}
func getMultimediaError(error: GetMultimediaErrorFatal){
let errorAlert = UIAlertView(title: "Error", message: error.message, delegate: nil, cancelButtonTitle: "Close")
errorAlert.show()
}
}
|
27c07423b4f6f6b2ab7d382820e181e8
| 29.28169 | 119 | 0.651163 | false | false | false | false |
uber/rides-ios-sdk
|
refs/heads/master
|
source/UberRidesTests/ObjectMappingTests.swift
|
mit
|
1
|
//
// ObjectMappingTests.swift
// UberRidesTests
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import UberCore
@testable import UberRides
class ObjectMappingTests: XCTestCase {
override func setUp() {
super.setUp()
Configuration.restoreDefaults()
Configuration.shared.isSandbox = true
}
override func tearDown() {
Configuration.restoreDefaults()
super.tearDown()
}
/**
Tests mapping result of GET /v1/product/{product_id} endpoint.
*/
func testGetProduct() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProductID", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let product = try? JSONDecoder.uberDecoder.decode(Product.self, from: jsonData)
XCTAssertNotNil(product)
XCTAssertEqual(product!.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(product!.name, "uberX")
XCTAssertEqual(product!.productDescription, "THE LOW-COST UBER")
XCTAssertEqual(product!.capacity, 4)
XCTAssertEqual(product!.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png")!)
let priceDetails = product!.priceDetails
XCTAssertNotNil(priceDetails)
XCTAssertEqual(priceDetails!.distanceUnit, "mile")
XCTAssertEqual(priceDetails!.costPerMinute, 0.22)
XCTAssertEqual(priceDetails!.minimumFee, 7.0)
XCTAssertEqual(priceDetails!.costPerDistance, 1.15)
XCTAssertEqual(priceDetails!.baseFee, 2.0)
XCTAssertEqual(priceDetails!.cancellationFee, 5.0)
XCTAssertEqual(priceDetails!.currencyCode, "USD")
let serviceFees = priceDetails!.serviceFees
XCTAssertNotNil(serviceFees)
XCTAssertEqual(serviceFees?.count, 1)
XCTAssertEqual(serviceFees?.first?.name, "Booking fee")
XCTAssertEqual(serviceFees?.first?.fee, 2.0)
}
}
}
/**
Tests mapping of malformed result of GET /v1/products endpoint.
*/
func testGetProductBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProductID", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let product = try? JSONDecoder.uberDecoder.decode(UberProducts.self, from: jsonData)
XCTAssertNil(product)
}
}
}
/**
Tests mapping result of GET /v1/products/{product_id} endpoint.
*/
func testGetAllProducts() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProducts", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let products = try? JSONDecoder.uberDecoder.decode(UberProducts.self, from: jsonData)
XCTAssertNotNil(products)
XCTAssertNotNil(products!.list)
XCTAssertEqual(products!.list!.count, 9)
XCTAssertEqual(products!.list![0].name, "SELECT")
XCTAssertEqual(products!.list![1].name, "uberXL")
XCTAssertEqual(products!.list![2].name, "BLACK")
XCTAssertEqual(products!.list![3].name, "SUV")
XCTAssertEqual(products!.list![4].name, "ASSIST")
XCTAssertEqual(products!.list![5].name, "WAV")
XCTAssertEqual(products!.list![6].name, "POOL")
XCTAssertEqual(products!.list![7].name, "uberX")
XCTAssertEqual(products!.list![8].name, "TAXI")
/// Assert upfront fare product, POOL
let uberPool = products?.list?[6]
XCTAssertEqual(uberPool?.upfrontFareEnabled, true)
XCTAssertEqual(uberPool?.capacity, 2)
XCTAssertEqual(uberPool?.productID, "26546650-e557-4a7b-86e7-6a3942445247")
XCTAssertNil(uberPool?.priceDetails)
XCTAssertEqual(uberPool?.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png")!)
XCTAssertEqual(uberPool?.cashEnabled, false)
XCTAssertEqual(uberPool?.isShared, true)
XCTAssertEqual(uberPool?.name, "POOL")
XCTAssertEqual(uberPool?.productGroup, ProductGroup.rideshare)
XCTAssertEqual(uberPool?.productDescription, "Share the ride, split the cost.")
/// Assert time+distance product, uberX (pulled from Sydney)
let uberX = products?.list?[7]
XCTAssertEqual(uberX?.upfrontFareEnabled, false)
XCTAssertEqual(uberX?.capacity, 4)
XCTAssertEqual(uberX?.productID, "2d1d002b-d4d0-4411-98e1-673b244878b2")
XCTAssertEqual(uberX?.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png")!)
XCTAssertEqual(uberX?.cashEnabled, false)
XCTAssertEqual(uberX?.isShared, false)
XCTAssertEqual(uberX?.name, "uberX")
XCTAssertEqual(uberX?.productGroup, ProductGroup.uberX)
XCTAssertEqual(uberX?.productDescription, "Everyday rides that are always smarter than a taxi")
XCTAssertEqual(uberX?.priceDetails?.serviceFees?.first?.fee, 0.55)
XCTAssertEqual(uberX?.priceDetails?.serviceFees?.first?.name, "Booking fee")
XCTAssertEqual(uberX?.priceDetails?.costPerMinute, 0.4)
XCTAssertEqual(uberX?.priceDetails?.distanceUnit, "km")
XCTAssertEqual(uberX?.priceDetails?.minimumFee, 9)
XCTAssertEqual(uberX?.priceDetails?.costPerDistance, 1.45)
XCTAssertEqual(uberX?.priceDetails?.baseFee, 2.5)
XCTAssertEqual(uberX?.priceDetails?.cancellationFee, 10)
XCTAssertEqual(uberX?.priceDetails?.currencyCode, "AUD")
/// Assert hail product, TAXI
let taxi = products?.list?[8]
XCTAssertEqual(taxi?.upfrontFareEnabled, false)
XCTAssertEqual(taxi?.capacity, 4)
XCTAssertEqual(taxi?.productID, "3ab64887-4842-4c8e-9780-ccecd3a0391d")
XCTAssertNil(uberPool?.priceDetails)
XCTAssertEqual(taxi?.imageURL, URL(string: "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-taxi.png")!)
XCTAssertEqual(taxi?.cashEnabled, false)
XCTAssertEqual(taxi?.isShared, false)
XCTAssertEqual(taxi?.name, "TAXI")
XCTAssertEqual(taxi?.productGroup, ProductGroup.taxi)
XCTAssertEqual(taxi?.productDescription, "TAXI WITHOUT THE HASSLE")
}
}
}
/**
Tests mapping of malformed result of GET /v1/products endpoint.
*/
func testGetAllProductsBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getProducts", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let products = try? JSONDecoder.uberDecoder.decode(UberProducts.self, from: jsonData)
XCTAssertNil(products)
}
}
}
/**
Tests mapping result of GET /v1.2/estimates/time
*/
func testGetTimeEstimates() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getTimeEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let timeEstimates = try? JSONDecoder.uberDecoder.decode(TimeEstimates.self, from: jsonData)
XCTAssertNotNil(timeEstimates)
XCTAssertNotNil(timeEstimates!.list)
let list = timeEstimates!.list!
XCTAssertEqual(timeEstimates!.list!.count, 4)
XCTAssertEqual(list[0].productID, "5f41547d-805d-4207-a297-51c571cf2a8c")
XCTAssertEqual(list[0].estimate, 410)
XCTAssertEqual(list[0].name, "UberBLACK")
XCTAssertEqual(list[1].name, "UberSUV")
XCTAssertEqual(list[2].name, "uberTAXI")
XCTAssertEqual(list[3].name, "uberX")
}
}
}
/**
Tests mapping of malformed result of GET /v1.2/estimates/time
*/
func testGetTimeEstimatesBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getTimeEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let timeEstimates = try? JSONDecoder.uberDecoder.decode(TimeEstimates.self, from: jsonData)
XCTAssertNil(timeEstimates)
}
}
}
/**
Tests mapping result of GET /v1.2/estimates/price endpoint.
*/
func testGetPriceEstimates() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getPriceEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
var priceEstimates: PriceEstimates?
do {
priceEstimates = try JSONDecoder.uberDecoder.decode(PriceEstimates.self, from: jsonData)
} catch let e {
XCTFail(e.localizedDescription)
}
XCTAssertNotNil(priceEstimates)
XCTAssertNotNil(priceEstimates!.list)
let list = priceEstimates!.list!
XCTAssertEqual(list.count, 4)
XCTAssertEqual(list[0].productID, "08f17084-23fd-4103-aa3e-9b660223934b")
XCTAssertEqual(list[0].currencyCode, "USD")
XCTAssertEqual(list[0].name, "UberBLACK")
XCTAssertEqual(list[0].estimate, "$23-29")
XCTAssertEqual(list[0].lowEstimate, 23)
XCTAssertEqual(list[0].highEstimate, 29)
XCTAssertEqual(list[0].surgeMultiplier, 1)
XCTAssertEqual(list[0].duration, 640)
XCTAssertEqual(list[0].distance, 5.34)
}
}
}
/**
Tests mapping of malformed result of GET /v1.2/estimates/price endpoint.
*/
func testGetPriceEstimatesBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getPriceEstimates", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let priceEstimates = try? JSONDecoder.uberDecoder.decode(PriceEstimates.self, from: jsonData)
XCTAssertNil(priceEstimates)
}
}
}
/**
Tests mapping result of GET /v1.2/history
*/
func testGetTripHistory() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getHistory", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let userActivity = try? JSONDecoder.uberDecoder.decode(TripHistory.self, from: jsonData)
XCTAssertNotNil(userActivity)
XCTAssertNotNil(userActivity!.history)
XCTAssertEqual(userActivity!.count, 1)
XCTAssertEqual(userActivity!.limit, 5)
XCTAssertEqual(userActivity!.offset, 0)
let history = userActivity!.history
XCTAssertEqual(history.count, 1)
XCTAssertEqual(history[0].status, RideStatus.completed)
XCTAssertEqual(history[0].distance, 1.64691465)
XCTAssertEqual(history[0].requestTime, Date(timeIntervalSince1970: 1428876188))
XCTAssertEqual(history[0].startTime, Date(timeIntervalSince1970: 1428876374))
XCTAssertEqual(history[0].endTime, Date(timeIntervalSince1970: 1428876927))
XCTAssertEqual(history[0].requestID, "37d57a99-2647-4114-9dd2-c43bccf4c30b")
XCTAssertEqual(history[0].productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertNotNil(history[0].startCity)
let city = history[0].startCity
XCTAssertEqual(city?.name, "San Francisco")
XCTAssertEqual(city?.latitude, 37.7749295)
XCTAssertEqual(city?.longitude, -122.4194155)
}
}
}
/**
Tests mapping of malformed result of GET /v1.2/history endpoint.
*/
func testGetHistoryBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getHistory", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
// Represent some bad JSON
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let userActivity = try? JSONDecoder.uberDecoder.decode(TripHistory.self, from: jsonData)
XCTAssertNil(userActivity)
}
}
}
/**
Tests mapping result of GET /v1/me endpoint.
*/
func testGetUserProfile() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getMe", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let userProfile = try? JSONDecoder.uberDecoder.decode(UserProfile.self, from: jsonData)
XCTAssertNotNil(userProfile)
XCTAssertEqual(userProfile!.firstName, "Uber")
XCTAssertEqual(userProfile!.lastName, "Developer")
XCTAssertEqual(userProfile!.email, "[email protected]")
XCTAssertEqual(userProfile!.picturePath, "https://profile-picture.jpg")
XCTAssertEqual(userProfile!.promoCode, "teypo")
XCTAssertEqual(userProfile!.UUID, "91d81273-45c2-4b57-8124-d0165f8240c0")
XCTAssertEqual(userProfile!.riderID, "kIN8tMqcXMSJt1VC3HWNF0H4VD1JKlJkY==")
}
}
}
/**
Tests mapping of malformed result of GET /v1/me endpoint.
*/
func testGetUserProfileBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getMe", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
let jsonData = JSONString.replacingOccurrences(of: "{", with: "").data(using: .utf8)!
let userProfile = try? JSONDecoder.uberDecoder.decode(UserProfile.self, from: jsonData)
XCTAssertNil(userProfile)
}
}
}
/**
Tests mapping result of POST /v1/requests
*/
func testPostRequest() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "postRequests", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertNotNil(trip)
XCTAssertEqual(trip.requestID, "852b8fdd-4369-4659-9628-e122662ad257")
XCTAssertEqual(trip.status, RideStatus.processing)
XCTAssertNil(trip.vehicle)
XCTAssertNil(trip.driver)
XCTAssertNil(trip.driverLocation)
XCTAssertEqual(trip.surgeMultiplier, 1.0)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestProcessing() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestProcessing", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "43faeac4-1634-4a0c-9826-783e3a3d1668")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.processing)
XCTAssertEqual(trip.isShared, false)
XCTAssertNil(trip.driverLocation)
XCTAssertNil(trip.vehicle)
XCTAssertNil(trip.driver)
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7759792)
XCTAssertEqual(trip.pickup!.longitude, -122.41823)
XCTAssertNil(trip.pickup!.eta)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7259792)
XCTAssertEqual(trip.destination!.longitude, -122.42823)
XCTAssertNil(trip.destination!.eta)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestAccepted() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestAccepted", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "17cb78a7-b672-4d34-a288-a6c6e44d5315")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.accepted)
XCTAssertEqual(trip.isShared, false)
XCTAssertEqual(trip.surgeMultiplier, 1.0)
XCTAssertNotNil(trip.driverLocation)
XCTAssertEqual(trip.driverLocation!.latitude, 37.7886532015)
XCTAssertEqual(trip.driverLocation!.longitude, -122.3961987534)
XCTAssertEqual(trip.driverLocation!.bearing, 135)
XCTAssertNotNil(trip.vehicle)
XCTAssertEqual(trip.vehicle!.make, "Bugatti")
XCTAssertEqual(trip.vehicle!.model, "Veyron")
XCTAssertEqual(trip.vehicle!.licensePlate, "I<3Uber")
XCTAssertEqual(trip.vehicle!.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/car.jpeg")!)
XCTAssertNotNil(trip.driver)
XCTAssertEqual(trip.driver!.name, "Bob")
XCTAssertEqual(trip.driver!.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/img.jpeg")!)
XCTAssertEqual(trip.driver!.phoneNumber, "+14155550000")
XCTAssertEqual(trip.driver!.smsNumber, "+14155550000")
XCTAssertEqual(trip.driver!.rating, 5)
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7872486012)
XCTAssertEqual(trip.pickup!.longitude, -122.4026315287)
XCTAssertEqual(trip.pickup!.eta, 5)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7766874)
XCTAssertEqual(trip.destination!.longitude, -122.394857)
XCTAssertEqual(trip.destination!.eta, 19)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestArriving() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestArriving", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "a274f565-cdb7-4a64-947d-042dfd185eed")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.arriving)
XCTAssertEqual(trip.isShared, false)
XCTAssertNotNil(trip.driverLocation)
XCTAssertEqual(trip.driverLocation?.latitude, 37.7751956968)
XCTAssertEqual(trip.driverLocation?.longitude, -122.4174361781)
XCTAssertEqual(trip.driverLocation?.bearing, 310)
XCTAssertNotNil(trip.vehicle)
XCTAssertEqual(trip.vehicle?.make, "Oldsmobile")
XCTAssertNil(trip.vehicle?.pictureURL)
XCTAssertEqual(trip.vehicle?.model, "Alero")
XCTAssertEqual(trip.vehicle?.licensePlate, "123-XYZ")
XCTAssertNotNil(trip.driver)
XCTAssertEqual(trip.driver?.phoneNumber, "+16504886027")
XCTAssertEqual(trip.driver?.rating, 5)
XCTAssertEqual(trip.driver?.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/4615701cdfbb033148d4.jpeg")!)
XCTAssertEqual(trip.driver?.name, "Edward")
XCTAssertEqual(trip.driver?.smsNumber, "+16504886027")
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7759792)
XCTAssertEqual(trip.pickup!.longitude, -122.41823)
XCTAssertEqual(trip.pickup!.eta, 1)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7259792)
XCTAssertEqual(trip.destination!.longitude, -122.42823)
XCTAssertEqual(trip.destination!.eta, 16)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestInProgress() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestInProgress", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "a274f565-cdb7-4a64-947d-042dfd185eed")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.inProgress)
XCTAssertEqual(trip.isShared, false)
XCTAssertNotNil(trip.driverLocation)
XCTAssertEqual(trip.driverLocation?.latitude, 37.7751956968)
XCTAssertEqual(trip.driverLocation?.longitude, -122.4174361781)
XCTAssertEqual(trip.driverLocation?.bearing, 310)
XCTAssertNotNil(trip.vehicle)
XCTAssertEqual(trip.vehicle?.make, "Oldsmobile")
XCTAssertNil(trip.vehicle?.pictureURL)
XCTAssertEqual(trip.vehicle?.model, "Alero")
XCTAssertEqual(trip.vehicle?.licensePlate, "123-XYZ")
XCTAssertNotNil(trip.driver)
XCTAssertEqual(trip.driver?.phoneNumber, "+16504886027")
XCTAssertEqual(trip.driver?.rating, 5)
XCTAssertEqual(trip.driver?.pictureURL, URL(string: "https://d1w2poirtb3as9.cloudfront.net/4615701cdfbb033148d4.jpeg")!)
XCTAssertEqual(trip.driver?.name, "Edward")
XCTAssertEqual(trip.driver?.smsNumber, "+16504886027")
XCTAssertNotNil(trip.pickup)
XCTAssertEqual(trip.pickup!.latitude, 37.7759792)
XCTAssertEqual(trip.pickup!.longitude, -122.41823)
XCTAssertNil(trip.pickup!.eta)
XCTAssertNotNil(trip.destination)
XCTAssertEqual(trip.destination!.latitude, 37.7259792)
XCTAssertEqual(trip.destination!.longitude, -122.42823)
XCTAssertEqual(trip.destination!.eta, 16)
}
}
}
/**
Tests mapping result of GET /v1/requests/current or /v1/requests/{request_id}
*/
func testGetRequestCompleted() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getRequestCompleted", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let trip = try? JSONDecoder.uberDecoder.decode(Ride.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(trip.requestID, "a274f565-cdb7-4a64-947d-042dfd185eed")
XCTAssertEqual(trip.productID, "a1111c8c-c720-46c3-8534-2fcdd730040d")
XCTAssertEqual(trip.status, RideStatus.completed)
XCTAssertEqual(trip.isShared, false)
XCTAssertNil(trip.driverLocation)
XCTAssertNil(trip.vehicle)
XCTAssertNil(trip.driver)
XCTAssertNil(trip.pickup)
XCTAssertNil(trip.destination)
}
}
}
/**
Tests mapping of POST /v1.2/requests/estimate endpoint.
*/
func testGetRequestEstimate() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "requestEstimate", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
var estimate: RideEstimate?
do {
estimate = try JSONDecoder.uberDecoder.decode(RideEstimate.self, from: jsonData)
}
catch let e {
XCTFail(e.localizedDescription)
}
XCTAssertNotNil(estimate)
XCTAssertEqual(estimate!.pickupEstimate, 2)
XCTAssertNotNil(estimate?.fare)
XCTAssertEqual(estimate?.fare?.breakdown?.first?.name, "Base Fare")
XCTAssertEqual(estimate?.fare?.breakdown?.first?.type, UpfrontFareComponentType.baseFare)
XCTAssertEqual(estimate?.fare?.breakdown?.first?.value, 11.95)
XCTAssertEqual(estimate?.fare?.value, 11.95)
XCTAssertEqual(estimate?.fare?.fareID, "3d957d6ab84e88209b6778d91bd4df3c12d17b60796d89793d6ed01650cbabfe")
XCTAssertEqual(estimate?.fare?.expiresAt, Date(timeIntervalSince1970: 1503702982))
XCTAssertEqual(estimate?.fare?.display, "$11.95")
XCTAssertEqual(estimate?.fare?.currencyCode, "USD")
XCTAssertNotNil(estimate!.distanceEstimate)
XCTAssertEqual(estimate!.distanceEstimate!.distance, 5.35)
XCTAssertEqual(estimate!.distanceEstimate!.duration, 840)
XCTAssertEqual(estimate!.distanceEstimate!.distanceUnit, "mile")
}
}
}
/**
Tests mapping of POST /v1.2/requests/estimate endpoint for a city w/o upfront pricing.
*/
func testGetRequestEstimateNoUpfront() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "requestEstimateNoUpfront", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let estimate = try? JSONDecoder.uberDecoder.decode(RideEstimate.self, from: jsonData)
XCTAssertNotNil(estimate)
XCTAssertEqual(estimate!.pickupEstimate, 2)
XCTAssertNotNil(estimate!.priceEstimate)
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationURL, URL(string: "https://api.uber.com/v1/surge-confirmations/7d604f5e"))
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationID, "7d604f5e")
XCTAssertNotNil(estimate!.distanceEstimate)
XCTAssertEqual(estimate!.distanceEstimate!.distance, 4.87)
XCTAssertEqual(estimate!.distanceEstimate!.duration, 660)
XCTAssertEqual(estimate!.distanceEstimate!.distanceUnit, "mile")
}
}
}
func testGetRequestEstimateNoCars() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "requestEstimateNoCars", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let estimate = try? JSONDecoder.uberDecoder.decode(RideEstimate.self, from: jsonData)
XCTAssertNotNil(estimate)
XCTAssertNil(estimate!.pickupEstimate)
XCTAssertNotNil(estimate!.priceEstimate)
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationURL, URL(string: "https://api.uber.com/v1/surge-confirmations/7d604f5e"))
XCTAssertEqual(estimate!.priceEstimate?.surgeConfirmationID, "7d604f5e")
XCTAssertNotNil(estimate!.distanceEstimate)
XCTAssertEqual(estimate!.distanceEstimate!.distance, 4.87)
XCTAssertEqual(estimate!.distanceEstimate!.duration, 660)
XCTAssertEqual(estimate!.distanceEstimate!.distanceUnit, "mile")
}
}
}
/**
Tests mapping of GET v1/places/{place_id} endpoint
*/
func testGetPlace() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "place", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let place = try? JSONDecoder.uberDecoder.decode(Place.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(place.address, "685 Market St, San Francisco, CA 94103, USA")
return
}
}
XCTAssert(false)
}
/**
Tests mapping of GET /v1/payment-methods endpoint.
*/
func testGetPaymentMethods() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "getPaymentMethods", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let paymentMethods = try? JSONDecoder.uberDecoder.decode(PaymentMethods.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(paymentMethods.lastUsed, "f53847de-8113-4587-c307-51c2d13a823c")
guard let payments = paymentMethods.list else {
XCTAssert(false)
return
}
XCTAssertEqual(payments.count, 4)
XCTAssertEqual(payments[0].methodID, "5f384f7d-8323-4207-a297-51c571234a8c")
XCTAssertEqual(payments[1].methodID, "f33847de-8113-4587-c307-51c2d13a823c")
XCTAssertEqual(payments[2].methodID, "f43847de-8113-4587-c307-51c2d13a823c")
XCTAssertEqual(payments[3].methodID, "f53847de-8113-4587-c307-51c2d13a823c")
XCTAssertEqual(payments[0].type, "baidu_wallet")
XCTAssertEqual(payments[1].type, "alipay")
XCTAssertEqual(payments[2].type, "visa")
XCTAssertEqual(payments[3].type, "business_account")
XCTAssertEqual(payments[0].paymentDescription, "***53")
XCTAssertEqual(payments[1].paymentDescription, "ga***@uber.com")
XCTAssertEqual(payments[2].paymentDescription, "***23")
XCTAssertEqual(payments[3].paymentDescription, "Late Night Ride")
return
}
}
XCTAssert(false)
}
/**
Tests mapping of GET /v1/requests/{request_id}/receipt endpoint.
*/
func testGetRideReceipt() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "rideReceipt", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let receipt = try? JSONDecoder.uberDecoder.decode(RideReceipt.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(receipt.requestID, "f590713c-fe6b-438b-9da1-8aeeea430657")
let chargeAdjustments = receipt.chargeAdjustments
XCTAssertEqual(chargeAdjustments?.count, 1)
XCTAssertEqual(chargeAdjustments?.first?.name, "Booking Fee")
XCTAssertEqual(chargeAdjustments?.first?.type, "booking_fee")
XCTAssertEqual(receipt.subtotal, "$12.78")
XCTAssertEqual(receipt.totalCharged, "$5.92")
XCTAssertEqual(receipt.totalFare, "$12.79")
XCTAssertEqual(receipt.totalOwed, 0.0)
XCTAssertEqual(receipt.currencyCode, "USD")
XCTAssertEqual(receipt.duration?.hour, 0)
XCTAssertEqual(receipt.duration?.minute, 11)
XCTAssertEqual(receipt.duration?.second, 32)
XCTAssertEqual(receipt.distance, "1.87")
XCTAssertEqual(receipt.distanceLabel, "miles")
return
}
}
XCTAssert(false)
}
/**
Test bad JSON for GET /v1/reqeuests/{request_id}/receipt
*/
func testGetRideReceiptBadJSON() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "rideReceipt", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let JSONString = String(data: jsonData, encoding: String.Encoding.utf8)!
let jsonData = JSONString.replacingOccurrences(of: "[", with: "").data(using: .utf8)!
let receipt = try? JSONDecoder.uberDecoder.decode(RideReceipt.self, from: jsonData)
XCTAssertNil(receipt)
return
}
}
XCTAssert(false)
}
/**
Tests mapping of GET /v1/requests/{request_id}/map endpoint.
*/
func testGetRideMap() {
let bundle = Bundle(for: ObjectMappingTests.self)
if let path = bundle.path(forResource: "rideMap", ofType: "json") {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) {
guard let map = try? JSONDecoder.uberDecoder.decode(RideMap.self, from: jsonData) else {
XCTAssert(false)
return
}
XCTAssertEqual(map.path, URL(string: "https://trip.uber.com/abc123")!)
XCTAssertEqual(map.requestID, "b5512127-a134-4bf4-b1ba-fe9f48f56d9d")
return
}
}
XCTAssert(false)
}
}
|
dd2afa6080785abc088208d3345320a5
| 46.45601 | 146 | 0.599316 | false | true | false | false |
6ag/AppScreenshots
|
refs/heads/master
|
AppScreenshots/Classes/Module/Home/View/JFPasterStageView.swift
|
mit
|
1
|
//
// JFPasterStageView.swift
// AppScreenshots
//
// Created by zhoujianfeng on 2017/2/21.
// Copyright © 2017年 zhoujianfeng. All rights reserved.
//
import UIKit
protocol JFPasterStageViewDelegate: NSObjectProtocol {
func didTappedBgView()
}
class JFPasterStageView: UIView {
weak var delegate: JFPasterStageViewDelegate?
/// 贴纸集合
fileprivate var pasterList = [JFPasterView]()
/// 当前贴图
fileprivate var pasterCurrent: JFPasterView? {
didSet {
self.bringSubview(toFront: pasterCurrent!)
}
}
// 记录贴纸的id
fileprivate var newPasterID: Int = 0
/// 原图
public var originImage: UIImage? {
didSet {
self.imgView.image = originImage
}
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 准备UI
private func prepareUI() {
addSubview(bgButton)
addSubview(imgView)
}
/**
添加贴图
- param: imgPater 贴图图片
*/
public func addPasterWithImg(imgPater: UIImage) {
clearAllOnFirst()
newPasterID += 1
pasterCurrent = JFPasterView(pasterStageView: self, pasterID: newPasterID, imagePaster: imgPater)
pasterCurrent?.delegate = self
pasterList.append(pasterCurrent!)
addSubview(pasterCurrent!)
}
/// 获取已经贴图后的图片
///
/// - Returns: 贴纸后生成的新图
public func doneEdit() -> UIImage {
clearAllOnFirst()
return getImageFromView(theView: self)
}
/// 将UIView转成UIImage
func getImageFromView(theView: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(theView.bounds.size, true, UIScreen.main.scale)
theView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
/// 点击了背景
func backgroundClicked(btBg: UIButton) {
clearAllOnFirst()
delegate?.didTappedBgView()
}
/**
清除贴纸操作状态
*/
func clearAllOnFirst() {
pasterCurrent?.isOnFirst = false
for paster in pasterList {
paster.isOnFirst = false
}
}
// MARK: - 懒加载
/**
背景按钮
*/
fileprivate lazy var bgButton: UIButton = {
let button = UIButton(frame: self.frame)
button.tintColor = nil
button.backgroundColor = nil
button.addTarget(self, action: #selector(backgroundClicked(btBg:)), for: .touchUpInside)
return button
}()
/**
需要编辑的视图
*/
fileprivate lazy var imgView: UIImageView = {
let imageView = UIImageView(frame: UIScreen.main.bounds)
return imageView
}()
}
// MARK: - JFPasterViewDelegate
extension JFPasterStageView: JFPasterViewDelegate {
/**
让指定贴纸成为第一响应者
- param: pasterID 贴纸id
*/
func makePasterBecomeFirstRespond(pasterID: Int) {
for paster in pasterList {
paster.isOnFirst = false
if paster.pasterID == pasterID {
pasterCurrent = paster
paster.isOnFirst = true
}
}
}
/**
移除指定贴纸
- param: pasterID 贴纸id
*/
func removePaster(pasterID: Int) {
for (index, paster) in pasterList.enumerated() {
if paster.pasterID == pasterID {
pasterList.remove(at: index)
break
}
}
}
}
|
dce5f0ba4dde37ca1648c3ee97db7031
| 22.18239 | 105 | 0.57949 | false | false | false | false |
itsbriany/Sudoku
|
refs/heads/master
|
Sudoku/SudokuViewController.swift
|
apache-2.0
|
1
|
//
// SudokuViewController.swift
// Sudoku
//
// Created by Brian Yip on 2016-01-26.
// Copyright © 2016 Brian Yip. All rights reserved.
//
import UIKit
class SudokuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet var mainView: UIView!
@IBOutlet weak var sudokuInputCollectionView: UICollectionView!
@IBOutlet weak var sudokuCollectionView: UICollectionView!
@IBOutlet weak var gameStatus: UILabel!
@IBOutlet weak var sudokuLevel: UINavigationItem!
let inputButtons = 9
let sudokuCellIdentifier = "SudokuCollectionViewCell"
let sudokuButtonCellIdentifier = "SudokuButtonCollectionViewCell"
let levelSelectionSegue = "SelectLevelSegue"
let homeSegue = "HomeSegue"
let sudokuCollectionViewCellBorderColor = UIColor.blackColor().CGColor
let selectedSudokuCollectionViewCellBorderColor = UIColor.yellowColor().CGColor
let selectedSudokuCollectionViewCellBorderWidth: CGFloat = 3
let inputSudokuCollectionViewCellBorderWidth: CGFloat = 2
let sudokuCollectionViewCellBorderWidth: CGFloat = 1
let winText = "You did it! 👍"
let loseText = "Nope, that's not it. ¯\\_(ツ)_/¯"
var sudokuManager: SudokuManager?
var selectedSudokuCell: SudokuCollectionViewCell?
// Initialization
override func viewDidLoad() {
super.viewDidLoad()
self.sudokuLevel.title = "Level " + String(self.sudokuManager!.sudokuIndex + 1)
}
// Cell count
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if (collectionView == self.sudokuInputCollectionView) {
return self.inputButtons
}
if (collectionView == self.sudokuCollectionView) {
return getSudokuCollectionViewCells().count
}
return getSudokuCollectionViewCells().count
}
// Load the cells in the collection view
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if (collectionView == self.sudokuCollectionView) {
return loadSudokuCollectionViewCell(collectionView, cellForItemAtIndexPath: indexPath)
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.sudokuButtonCellIdentifier, forIndexPath: indexPath) as! SudokuButtonCollectionViewCell
formatInputCell(cell, indexPath: indexPath)
return cell
}
// Selection behaviour
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if (collectionView == self.sudokuCollectionView) {
resetSelectedCellBorder()
selectCell(didSelectItemAtIndexPath: indexPath)
highlightSelectedCellBorder()
return
}
}
// Dimensions of each cell
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return customCellFrame(indexPath)
}
// MARK: User Actions
// Click on an input cell
@IBAction func updateSelection(sender: UIButton) {
if ((self.selectedSudokuCell) != nil) {
self.selectedSudokuCell!.value.text = sender.titleLabel?.text
self.selectedSudokuCell!.value.alpha = 0
self.sudokuManager!.fadeInCell(self.selectedSudokuCell!)
let index = self.sudokuCollectionView.indexPathForCell(self.selectedSudokuCell!)
let row = index!.row / sudokuManager!.format!.rows
let column = index!.row % sudokuManager!.format!.columns
let value: Int = Int(self.selectedSudokuCell!.value.text!)!
self.sudokuManager!.updateActiveSudoku(row, columnIndex: column, value: value)
return
}
}
@IBAction func checkSudoku(sender: UIBarButtonItem) {
self.gameStatus.hidden = false
flipGameStatusLabel()
if (self.sudokuManager!.activeSudoku!.isSolved()) {
self.gameStatus.textColor = UIColor.blueColor()
self.gameStatus.text = self.winText;
return
}
self.gameStatus.textColor = UIColor.redColor()
self.gameStatus.text = self.loseText
}
@IBAction func resetSudoku(sender: UIBarButtonItem) {
self.sudokuManager!.resetActiveSudoku()
refreshSudokuCollectionView()
}
@IBAction func solveSudoku(sender: AnyObject) {
self.sudokuManager!.solveActiveSudoku()
refreshSudokuCollectionView()
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == self.levelSelectionSegue {
if let navigationController = segue.destinationViewController as? UINavigationController {
if let destination = navigationController.topViewController as? LevelViewController {
self.sudokuManager!.resetActiveSudoku()
destination.sudokuManager = self.sudokuManager
}
}
} else if segue.identifier == self.homeSegue {
if let navigationController = segue.destinationViewController as? UINavigationController {
if let destination = navigationController.topViewController as? HomeViewController {
self.sudokuManager!.resetActiveSudoku()
destination.sudokuManager = self.sudokuManager
}
}
}
}
// MARK: Helpers
private func formatSudokuCell(cell: SudokuCollectionViewCell, indexPath: NSIndexPath) {
cell.layer.borderWidth = self.sudokuCollectionViewCellBorderWidth
cell.layer.borderColor = self.sudokuCollectionViewCellBorderColor
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 3;
}
private func formatInputCell(cell: SudokuButtonCollectionViewCell, indexPath: NSIndexPath) {
cell.layer.borderWidth = self.inputSudokuCollectionViewCellBorderWidth
cell.layer.borderColor = self.sudokuCollectionViewCellBorderColor
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 3;
cell.value.setTitle(String(indexPath.row + 1), forState: .Normal)
}
private func customCellFrame(indexPath: NSIndexPath) -> CGSize {
let screenSize = sudokuCollectionView.bounds
let cellSize = screenSize.width / (CGFloat(self.sudokuManager!.format!.columns) + 3) // +3 to make up for padding and margins
return CGSize(width: cellSize, height: cellSize)
}
private func getSudokuCollectionViewCells() -> [SudokuCollectionViewCell!] {
let sudokuCollectionViewCells = [SudokuCollectionViewCell!](count: self.sudokuManager!.format!.rows * self.sudokuManager!.format!.columns, repeatedValue: nil)
return sudokuCollectionViewCells
}
private func resetSelectedCellBorder() {
if (self.selectedSudokuCell != nil) {
self.selectedSudokuCell!.layer.borderColor = self.sudokuCollectionViewCellBorderColor
self.selectedSudokuCell!.layer.borderWidth = self.sudokuCollectionViewCellBorderWidth
}
}
private func highlightSelectedCellBorder() {
self.selectedSudokuCell!.layer.borderColor = self.selectedSudokuCollectionViewCellBorderColor
self.selectedSudokuCell!.layer.borderWidth = self.selectedSudokuCollectionViewCellBorderWidth
}
private func selectCell(didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = self.sudokuCollectionView.cellForItemAtIndexPath(indexPath) as! SudokuCollectionViewCell
self.selectedSudokuCell = cell
}
private func loadSudokuCollectionViewCell(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> SudokuCollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.sudokuCellIdentifier, forIndexPath: indexPath) as! SudokuCollectionViewCell
formatSudokuCell(cell, indexPath: indexPath)
self.sudokuManager!.loadSudokuValueIntoCell(indexPath, cell: cell, firstLoad: true)
return cell
}
private func refreshSudokuCollectionView() {
for indexPath in self.sudokuCollectionView.indexPathsForVisibleItems() {
let cell = self.sudokuCollectionView.cellForItemAtIndexPath(indexPath) as! SudokuCollectionViewCell
self.sudokuManager!.loadSudokuValueIntoCell(indexPath, cell: cell, firstLoad: false)
}
}
private func flipGameStatusLabel() {
UIView.transitionWithView(self.gameStatus, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromBottom, animations: {
() -> Void in
}, completion: {
(success) -> Void in
})
}
}
|
622d7bd62fb24d457f8af0e1db823092
| 44.05 | 169 | 0.701299 | false | false | false | false |
kmikiy/SpotMenu
|
refs/heads/master
|
SpotMenu/Preferences/Tabs/AboutPreferencesVC.swift
|
mit
|
1
|
//
// AboutPreferencesVC.swift
// SpotMenu
//
// Created by Miklós Kristyán on 2017. 12. 03..
// Copyright © 2017. KM. All rights reserved.
//
import Cocoa
class AboutPrefState {
var lastPressed: NSButton?
}
class AboutPrefProps {
var buttons: [NSButton] = []
let btc = "1Cc79kaUUWZ2fD7iFAnr5i89vb2j6JunvA"
let eth = "0xFA06Af34fd45c0213fc909F22cA7241BBD94076f"
let ltc = "LS3ibFQWd2xz1ByZajrzS3Y787LgRwHYVE"
}
class AboutPreferencesVC: NSViewController {
@IBOutlet private var scrollView: NSScrollView!
@IBOutlet private var btcButton: NSButton!
@IBOutlet private var btcTextField: NSTextField!
@IBOutlet private var ethButton: NSButton!
@IBOutlet private var ethTextField: NSTextField!
@IBOutlet private var ltcButton: NSButton!
@IBOutlet private var ltcTextField: NSTextField!
private var state: AboutPrefState = AboutPrefState()
private var props: AboutPrefProps = AboutPrefProps()
@IBOutlet var ppTextView: NSTextView!
@IBOutlet var aboutDescTextField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
aboutDescTextField.stringValue = NSLocalizedString("about-description", comment: "")
}
override func viewDidAppear() {
super.viewDidAppear()
scrollView.flashScrollers()
props.buttons = [btcButton, ethButton, ltcButton]
ppTextView.isEditable = true
ppTextView.checkTextInDocument(nil)
ppTextView.isEditable = false
btcTextField.stringValue = props.btc
ethTextField.stringValue = props.eth
ltcTextField.stringValue = props.ltc
updateFields()
}
@IBAction func btcButtonAction(_: Any) {
copyToClipBoard(text: props.btc)
state.lastPressed = btcButton
updateFields()
}
@IBAction func ethButtonAction(_: Any) {
copyToClipBoard(text: props.eth)
state.lastPressed = ethButton
updateFields()
}
@IBAction func ltcButtonAction(_: Any) {
copyToClipBoard(text: props.ltc)
state.lastPressed = ltcButton
updateFields()
}
private func copyToClipBoard(text: String) {
let pasteBoard = NSPasteboard.general
pasteBoard.clearContents()
pasteBoard.writeObjects([text as NSString])
}
private func updateFields() {
for button in props.buttons {
if button === state.lastPressed {
button.title = NSLocalizedString("copied", comment: "")
button.state = .off
} else {
button.title = NSLocalizedString("copy", comment: "")
button.state = .on
}
}
}
}
|
c5bf6e3203ada2499c5f43784d89714d
| 26.009901 | 92 | 0.653226 | false | false | false | false |
cjbeauchamp/tvOSDashboard
|
refs/heads/master
|
Charts/Classes/Data/Implementations/Standard/BarChartDataSet.swift
|
apache-2.0
|
5
|
//
// BarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet
{
private func initialize()
{
self.highlightColor = NSUIColor.blackColor()
self.calcStackSize(yVals as! [BarChartDataEntry])
self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry])
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Data functions and accessors
/// the maximum number of bars that are stacked upon each other, this value
/// is calculated from the Entries that are added to the DataSet
private var _stackSize = 1
/// the overall entry count, including counting each stack-value individually
private var _entryCountStacks = 0
/// Calculates the total number of entries this DataSet represents, including
/// stacks. All values belonging to a stack are calculated separately.
private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!)
{
_entryCountStacks = 0
for (var i = 0; i < yVals.count; i++)
{
let vals = yVals[i].values
if (vals == nil)
{
_entryCountStacks++
}
else
{
_entryCountStacks += vals!.count
}
}
}
/// calculates the maximum stacksize that occurs in the Entries array of this DataSet
private func calcStackSize(yVals: [BarChartDataEntry]!)
{
for (var i = 0; i < yVals.count; i++)
{
if let vals = yVals[i].values
{
if vals.count > _stackSize
{
_stackSize = vals.count
}
}
}
}
public override func calcMinMax(start start : Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = start; i <= endValue; i++)
{
if let e = _yVals[i] as? BarChartDataEntry
{
if !e.value.isNaN
{
if e.values == nil
{
if e.value < _yMin
{
_yMin = e.value
}
if e.value > _yMax
{
_yMax = e.value
}
}
else
{
if -e.negativeSum < _yMin
{
_yMin = -e.negativeSum
}
if e.positiveSum > _yMax
{
_yMax = e.positiveSum
}
}
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the maximum number of bars that can be stacked upon another in this DataSet.
public var stackSize: Int
{
return _stackSize
}
/// - returns: true if this DataSet is stacked (stacksize > 1) or not.
public var isStacked: Bool
{
return _stackSize > 1 ? true : false
}
/// - returns: the overall entry count, including counting each stack-value individually
public var entryCountStacks: Int
{
return _entryCountStacks
}
/// array of labels used to describe the different values of the stacked bars
public var stackLabels: [String] = ["Stack"]
// MARK: - Styling functions and accessors
/// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width)
public var barSpace: CGFloat = 0.15
/// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value
public var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0)
/// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque)
public var highlightAlpha = CGFloat(120.0 / 255.0)
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! BarChartDataSet
copy._stackSize = _stackSize
copy._entryCountStacks = _entryCountStacks
copy.stackLabels = stackLabels
copy.barSpace = barSpace
copy.barShadowColor = barShadowColor
copy.highlightAlpha = highlightAlpha
return copy
}
}
|
320ffc196cf1e2b4f2428c52fa5ff203
| 27.71066 | 148 | 0.510168 | false | false | false | false |
lstanii-magnet/ChatKitSample-iOS
|
refs/heads/master
|
ChatMessenger/ChatMessenger/ViewControllers/ViewController.swift
|
apache-2.0
|
1
|
/*
* Copyright (c) 2016 Magnet Systems, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import ChatKit
//MARK: custom chat list controller
class ViewController: MMXChatListViewController {
//MARK: Internal Variables
var _chatViewController : MMXChatViewController?
@IBOutlet var menuButton : UIButton?
//MARK: Private Variables
private var revealLoaded : Bool = false
//MARK: Overrides
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !revealLoaded {
revealLoaded = true
if self.revealViewController() != nil {
menuButton?.addTarget(self.revealViewController(), action: #selector(self.revealViewController().revealToggle(_:)), forControlEvents: .TouchUpInside)
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
}
//Override default chatview with a custom one
override weak var currentChatViewController : MMXChatViewController? {
set {
var controller : MMXChatViewController?
if let channel = newValue?.channel {
controller = CustomChatViewController(channel: channel)
} else if let users = newValue?.recipients {
controller = CustomChatViewController(recipients: users)
}
_chatViewController = controller
_chatViewController?.title = newValue?.title
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
if let name = _chatViewController?.channel?.name where name.hasPrefix("global_") {
_chatViewController?.collectionView?.backgroundColor = UIColor.purpleColor()
_chatViewController?.outgoingBubbleImageView = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleGreenColor())
}
}
get {
return _chatViewController
}
}
var customDatasource : ChatListControllerDatasource {
get {
let customDatasource = HomeChatListDatasource()
customDatasource.controller = self
return customDatasource
}
}
override var datasource: ChatListControllerDatasource? {
set { }
get {
return customDatasource
}
}
override func viewDidLoad() {
//added custom datasource for chats current user owns
let customDelegate = CustomChatListDelegate()
customDelegate.controller = self
self.delegate = customDelegate
super.viewDidLoad()
self.cellBackgroundColor = UIColor(red: 255.0/255.0, green: 243.0/255.0, blue: 233.0/255.0, alpha: 1.0)
self.tableView.backgroundColor = self.cellBackgroundColor
}
}
|
d37e7982b95f6a9f35a31deef854c123
| 31.378378 | 170 | 0.642181 | false | false | false | false |
EdwaRen/Recycle_Can_iOS
|
refs/heads/master
|
Recycle_Can/Recycle Can/LocationSearchTable.swift
|
mit
|
1
|
//
// LocationSearchTable.swift
// MapKitTutorial
//
// Created by Robert Chen on 12/28/15.
// Copyright © 2015 Thorn Technologies. All rights reserved.
//
import UIKit
import MapKit
class LocationSearchTable: UITableViewController {
weak var handleMapSearchDelegate: HandleMapSearch?
var matchingItems: [MKMapItem] = []
var mapView: MKMapView?
func parseAddress(_ selectedItem:MKPlacemark) -> String {
// put a space between "4" and "Melrose Place"
let firstSpace = (selectedItem.subThoroughfare != nil &&
selectedItem.thoroughfare != nil) ? " " : ""
// put a comma between street and city/state
let comma = (selectedItem.subThoroughfare != nil || selectedItem.thoroughfare != nil) &&
(selectedItem.subAdministrativeArea != nil || selectedItem.administrativeArea != nil) ? ", " : ""
// put a space between "Washington" and "DC"
let secondSpace = (selectedItem.subAdministrativeArea != nil &&
selectedItem.administrativeArea != nil) ? " " : ""
let addressLine = String(
format:"%@%@%@%@%@%@%@",
// street number
selectedItem.subThoroughfare ?? "",
firstSpace,
// street name
selectedItem.thoroughfare ?? "",
comma,
// city
selectedItem.locality ?? "",
secondSpace,
// state
selectedItem.administrativeArea ?? ""
)
return addressLine
}
}
extension LocationSearchTable : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let response = response else {
return
}
self.matchingItems = response.mapItems
self.tableView.reloadData()
}
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchingItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = matchingItems[indexPath.row].placemark
cell.textLabel?.text = selectedItem.name
cell.detailTextLabel?.text = parseAddress(selectedItem)
return cell
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedItem = matchingItems[indexPath.row].placemark
handleMapSearchDelegate?.dropPinZoomIn(selectedItem)
dismiss(animated: true, completion: nil)
}
}
|
3fedd6f50303bc38a4d100b74ead01fe
| 30.623762 | 109 | 0.615216 | false | false | false | false |
mominul/swiftup
|
refs/heads/master
|
Sources/libNix/libNix.swift
|
apache-2.0
|
1
|
import Glibc
import StringPlus
// This is only for compability...
public enum NixError: Error {
case errorOccurred
case fileOpenError
}
public func contentsOfDirectory(atPath path: String) throws -> [String] {
var contents : [String] = [String]()
let dir = opendir(path)
if dir == nil {
throw NixError.errorOccurred
}
defer {
closedir(dir!)
}
while let entry = readdir(dir!) {
let entryName = withUnsafePointer(to: &entry.pointee.d_name) {
String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}
// TODO: `entryName` should be limited in length to `entry.memory.d_namlen`.
if entryName != "." && entryName != ".." {
contents.append(entryName)
}
}
return contents
}
public func getContentsOf(file: String) throws -> String {
let fp = fopen(file, "r")
if fp == nil {
throw NixError.fileOpenError
}
let contents = UnsafeMutablePointer<CChar>.allocate(capacity: Int(BUFSIZ))
defer {
contents.deinitialize(count: Int(BUFSIZ))
contents.deallocate(capacity: Int(BUFSIZ))
fclose(fp)
}
fgets(contents, BUFSIZ, fp)
return String(cString: contents)
}
public func writeTo(file: String, with: String) throws {
let fp = fopen(file, "w")
if fp == nil {
throw NixError.errorOccurred
}
fputs(with, fp)
fclose(fp)
}
public func fileExists(atPath path: String) -> Bool {
var s = stat()
if lstat(path, &s) >= 0 {
// don't chase the link for this magic case -- we might be /Net/foo
// which is a symlink to /private/Net/foo which is not yet mounted...
if (s.st_mode & S_IFMT) == S_IFLNK {
if (s.st_mode & S_ISVTX) == S_ISVTX {
return true
}
// chase the link; too bad if it is a slink to /Net/foo
stat(path, &s)
}
} else {
return false
}
return true
}
public func createDirectory(atPath path: String) throws {
if !fileExists(atPath: path) {
let parent = path.deletingLastPathComponent
if !fileExists(atPath: parent) {
try createDirectory(atPath: parent)
}
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {
throw NixError.errorOccurred
}
}
}
|
d94965deeac1f08ceee0205a81403103
| 22.258065 | 80 | 0.643088 | false | false | false | false |
peiweichen/SurfingNavigationBar
|
refs/heads/master
|
SurfingNavigationBarDemo/SurfingNavigationBarDemo/DemoViewController3.swift
|
mit
|
1
|
//
// DemoViewController3.swift
// SurfingNavigationBarDemo
//
// Created by chenpeiwei on 6/15/16.
// Copyright © 2016 chenpeiwei. All rights reserved.
//
import UIKit
class DemoViewController3: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
titleLabel.contentMode = .Center
titleLabel.text = "TranslationYDemo"
let titleFont : UIFont = UIFont(name: "American Typewriter", size: 18.0)!
titleLabel.font = titleFont
titleLabel.textColor = UIColor.whiteColor()
self.navigationItem.titleView = titleLabel
self.tableView.backgroundColor = UIColor.blackColor()
self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cellIdentifier")
self.tableView.tableFooterView = UIView()
self.tableView.separatorStyle = .None
self.navigationController?.navigationBar.surfing_setBackgroundColor(UIColor(red: 208/255.0, green: 47/255.0, blue: 17/255.0, alpha: 1.0))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: nil)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "RightButton", style: .Plain, target: self, action: nil)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetY = (scrollView.contentOffset.y)
if offsetY > 0 {
if offsetY >= 64 {
setNavigationBarTranslationYProgress(1)
} else {
setNavigationBarTranslationYProgress(offsetY/64)
}
} else {
setNavigationBarTranslationYProgress(0)
}
}
func setNavigationBarTranslationYProgress(progress:CGFloat) {
self.navigationController?.navigationBar.surfing_setTranslationY(-64*progress)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier")
cell?.selectionStyle = .None
cell?.backgroundColor = UIColor.clearColor()
let imageView = UIImageView(image: UIImage(named: "surfing_sunset.jpg"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
cell?.contentView.addSubview(imageView)
cell?.contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: cell?.contentView, attribute: .Top, multiplier: 1, constant: 0))
cell?.contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Leading, relatedBy: .Equal, toItem: cell?.contentView, attribute: .Leading, multiplier: 1, constant: 0))
cell?.contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Trailing, relatedBy: .Equal, toItem: cell?.contentView, attribute: .Trailing, multiplier: 1, constant: 0))
cell?.contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: cell?.contentView, attribute: .Bottom, multiplier: 1, constant: 0))
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 300
}
}
|
8a374a0091a76cc9c3ae575fa4d5308b
| 39.617021 | 194 | 0.675746 | false | false | false | false |
Ferrari-lee/firefox-ios
|
refs/heads/autocomplete-highlight
|
Client/Frontend/Reader/ReaderModeStyleViewController.swift
|
mpl-2.0
|
27
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
private struct ReaderModeStyleViewControllerUX {
static let RowHeight = 50
static let Width = 270
static let Height = 4 * RowHeight
static let FontTypeRowBackground = UIColor(rgb: 0xfbfbfb)
static let FontTypeTitleFontSansSerif = UIFont(name: "FiraSans-Book", size: 16)
static let FontTypeTitleFontSerif = UIFont(name: "Charis SIL", size: 16)
static let FontTypeTitleSelectedColor = UIColor(rgb: 0x333333)
static let FontTypeTitleNormalColor = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeRowBackground = UIColor(rgb: 0xf4f4f4)
static let FontSizeLabelFontSansSerif = UIFont(name: "FiraSans-Book", size: 22)
static let FontSizeLabelFontSerif = UIFont(name: "Charis SIL", size: 22)
static let FontSizeLabelColor = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorEnabled = UIColor(rgb: 0x333333)
static let FontSizeButtonTextColorDisabled = UIColor.lightGrayColor() // TODO THis needs to be 44% of 0x333333
static let FontSizeButtonTextFont = UIFont(name: "FiraSans-Light", size: 22)
static let ThemeRowBackgroundColor = UIColor.whiteColor()
static let ThemeTitleFontSansSerif = UIFont(name: "FiraSans-Book", size: 15)
static let ThemeTitleFontSerif = UIFont(name: "Charis SIL", size: 15)
static let ThemeTitleColorLight = UIColor(rgb: 0x333333)
static let ThemeTitleColorDark = UIColor.whiteColor()
static let ThemeTitleColorSepia = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorLight = UIColor.whiteColor()
static let ThemeBackgroundColorDark = UIColor(rgb: 0x333333)
static let ThemeBackgroundColorSepia = UIColor(rgb: 0xF0E6DC)
static let BrightnessRowBackground = UIColor(rgb: 0xf4f4f4)
static let BrightnessSliderTintColor = UIColor(rgb: 0xe66000)
static let BrightnessSliderWidth = 140
static let BrightnessIconOffset = 10
}
// MARK: -
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
// MARK: -
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
private var fontTypeButtons: [FontTypeButton]!
private var fontSizeLabel: FontSizeLabel!
private var fontSizeButtons: [FontSizeButton]!
private var themeButtons: [ThemeButton]!
override func viewDidLoad() {
// Our preferred content size has a fixed width and height based on the rows + padding
preferredContentSize = CGSize(width: ReaderModeStyleViewControllerUX.Width, height: ReaderModeStyleViewControllerUX.Height)
popoverPresentationController?.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
// Font type row
let fontTypeRow = UIView()
view.addSubview(fontTypeRow)
fontTypeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
fontTypeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: "SELchangeFontType:")
// Font size row
let fontSizeRow = UIView()
view.addSubview(fontSizeRow)
fontSizeRow.backgroundColor = ReaderModeStyleViewControllerUX.FontSizeRowBackground
fontSizeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontTypeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
fontSizeLabel = FontSizeLabel()
fontSizeRow.addSubview(fontSizeLabel)
fontSizeLabel.snp_makeConstraints { (make) -> () in
make.center.equalTo(fontSizeRow)
return
}
fontSizeButtons = [
FontSizeButton(fontSizeAction: FontSizeAction.Smaller),
FontSizeButton(fontSizeAction: FontSizeAction.Bigger)
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: "SELchangeFontSize:")
// Theme row
let themeRow = UIView()
view.addSubview(themeRow)
themeRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(fontSizeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Sepia)
]
setupButtons(themeButtons, inRow: themeRow, action: "SELchangeTheme:")
// Brightness row
let brightnessRow = UIView()
view.addSubview(brightnessRow)
brightnessRow.backgroundColor = ReaderModeStyleViewControllerUX.BrightnessRowBackground
brightnessRow.snp_makeConstraints { (make) -> () in
make.top.equalTo(themeRow.snp_bottom)
make.left.right.equalTo(self.view)
make.height.equalTo(ReaderModeStyleViewControllerUX.RowHeight)
}
let slider = UISlider()
brightnessRow.addSubview(slider)
slider.accessibilityLabel = NSLocalizedString("Brightness", comment: "Accessibility label for brightness adjustment slider in Reader Mode display settings")
slider.tintColor = ReaderModeStyleViewControllerUX.BrightnessSliderTintColor
slider.addTarget(self, action: "SELchangeBrightness:", forControlEvents: UIControlEvents.ValueChanged)
slider.snp_makeConstraints { make in
make.center.equalTo(brightnessRow.center)
make.width.equalTo(ReaderModeStyleViewControllerUX.BrightnessSliderWidth)
}
let brightnessMinImageView = UIImageView(image: UIImage(named: "brightnessMin"))
brightnessRow.addSubview(brightnessMinImageView)
brightnessMinImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.right.equalTo(slider.snp_left).offset(-ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
let brightnessMaxImageView = UIImageView(image: UIImage(named: "brightnessMax"))
brightnessRow.addSubview(brightnessMaxImageView)
brightnessMaxImageView.snp_makeConstraints { (make) -> () in
make.centerY.equalTo(slider)
make.left.equalTo(slider.snp_right).offset(ReaderModeStyleViewControllerUX.BrightnessIconOffset)
}
selectFontType(readerModeStyle.fontType)
updateFontSizeButtons()
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.mainScreen().brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
private func setupButtons(buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in buttons.enumerate() {
row.addSubview(button)
button.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside)
button.snp_makeConstraints { make in
make.top.equalTo(row.snp_top)
if idx == 0 {
make.left.equalTo(row.snp_left)
} else {
make.left.equalTo(buttons[idx - 1].snp_right)
}
make.bottom.equalTo(row.snp_bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontType(fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.selected = (button.fontType == fontType)
}
for button in themeButtons {
button.fontType = fontType
}
fontSizeLabel.fontType = fontType
}
func SELchangeFontSize(button: FontSizeButton) {
switch button.fontSizeAction {
case .Smaller:
readerModeStyle.fontSize = readerModeStyle.fontSize.smaller()
case .Bigger:
readerModeStyle.fontSize = readerModeStyle.fontSize.bigger()
}
updateFontSizeButtons()
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func updateFontSizeButtons() {
for button in fontSizeButtons {
switch button.fontSizeAction {
case .Bigger:
button.enabled = !readerModeStyle.fontSize.isLargest()
break
case .Smaller:
button.enabled = !readerModeStyle.fontSize.isSmallest()
break
}
}
}
func SELchangeTheme(button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectTheme(theme: ReaderModeTheme) {
readerModeStyle.theme = theme
}
func SELchangeBrightness(slider: UISlider) {
UIScreen.mainScreen().brightness = CGFloat(slider.value)
}
}
// MARK: -
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType = .SansSerif
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRectZero)
self.fontType = fontType
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleSelectedColor, forState: UIControlState.Selected)
setTitleColor(ReaderModeStyleViewControllerUX.FontTypeTitleNormalColor, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.FontTypeRowBackground
accessibilityHint = NSLocalizedString("Changes font type.", comment: "Accessibility hint for the font type buttons in reader mode display settings")
switch fontType {
case .SansSerif:
setTitle(NSLocalizedString("Sans-serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
titleLabel?.font = f
case .Serif:
setTitle(NSLocalizedString("Serif", comment: "Font type setting in the reading view settings"), forState: UIControlState.Normal)
let f = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
titleLabel?.font = f
}
}
}
// MARK: -
enum FontSizeAction {
case Smaller
case Bigger
}
class FontSizeButton: UIButton {
var fontSizeAction: FontSizeAction = .Bigger
convenience init(fontSizeAction: FontSizeAction) {
self.init(frame: CGRectZero)
self.fontSizeAction = fontSizeAction
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorEnabled, forState: UIControlState.Normal)
setTitleColor(ReaderModeStyleViewControllerUX.FontSizeButtonTextColorDisabled, forState: UIControlState.Disabled)
switch fontSizeAction {
case .Smaller:
let smallerFontLabel = NSLocalizedString("-", comment: "Button for smaller reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
let smallerFontAccessibilityLabel = NSLocalizedString("Decrease text size", comment: "Accessibility label for button decreasing font size in display settings of reader mode")
setTitle(smallerFontLabel, forState: .Normal)
accessibilityLabel = smallerFontAccessibilityLabel
case .Bigger:
let largerFontLabel = NSLocalizedString("+", comment: "Button for larger reader font size. Keep this extremely short! This is shown in the reader mode toolbar.")
let largerFontAccessibilityLabel = NSLocalizedString("Increase text size", comment: "Accessibility label for button increasing font size in display settings of reader mode")
setTitle(largerFontLabel, forState: .Normal)
accessibilityLabel = largerFontAccessibilityLabel
}
// TODO Does this need to change with the selected font type? Not sure if makes sense for just +/-
titleLabel?.font = ReaderModeStyleViewControllerUX.FontSizeButtonTextFont
}
}
// MARK: -
class FontSizeLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
let fontSizeLabel = NSLocalizedString("Aa", comment: "Button for reader mode font size. Keep this extremely short! This is shown in the reader mode toolbar.")
text = fontSizeLabel
isAccessibilityElement = false
}
required init?(coder aDecoder: NSCoder) {
// TODO
fatalError("init(coder:) has not been implemented")
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSansSerif
case .Serif:
font = ReaderModeStyleViewControllerUX.FontSizeLabelFontSerif
}
}
}
}
// MARK: -
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRectZero)
self.theme = theme
setTitle(theme.rawValue, forState: UIControlState.Normal)
accessibilityHint = NSLocalizedString("Changes color theme.", comment: "Accessibility hint for the color theme setting buttons in reader mode display settings")
switch theme {
case .Light:
setTitle(NSLocalizedString("Light", comment: "Light theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorLight, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorLight
case .Dark:
setTitle(NSLocalizedString("Dark", comment: "Dark theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorDark, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorDark
case .Sepia:
setTitle(NSLocalizedString("Sepia", comment: "Sepia theme setting in Reading View settings"), forState: .Normal)
setTitleColor(ReaderModeStyleViewControllerUX.ThemeTitleColorSepia, forState: UIControlState.Normal)
backgroundColor = ReaderModeStyleViewControllerUX.ThemeBackgroundColorSepia
}
}
var fontType: ReaderModeFontType = .SansSerif {
didSet {
switch fontType {
case .SansSerif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSansSerif
case .Serif:
titleLabel?.font = ReaderModeStyleViewControllerUX.ThemeTitleFontSerif
}
}
}
}
|
49362d6103fe7daa059d70723b327875
| 40.6313 | 186 | 0.695361 | false | false | false | false |
Awalz/ark-ios-monitor
|
refs/heads/master
|
ArkMonitor/Settings/SettingsViewController.swift
|
mit
|
1
|
// Copyright (c) 2016 Ark
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
class SettingsViewController: ArkViewController {
fileprivate var tableView : ArkTableView!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Settings"
tableView = ArkTableView(CGRect.zero)
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
}
// MARK: UITableViewDelegate
extension SettingsViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 2,3:
return 85.0
default:
return 45.0
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let _ = tableView.cellForRow(at: indexPath) as? SettingsCurrencyTableViewCell {
let vc = CurrencySelectionViewController()
navigationController?.pushViewController(vc, animated: true)
}
if let _ = tableView.cellForRow(at: indexPath) as? SettingsServerTableViewCell {
let vc = ServerSelectionViewController()
navigationController?.pushViewController(vc, animated: true)
}
if let _ = tableView.cellForRow(at: indexPath) as? SettingsLogoutTableViewCell {
ArkDataManager.logoutOperations()
}
}
}
// MARK: UITableViewDataSource
extension SettingsViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let currency = ArkDataManager.currentCurrency
let cell = SettingsCurrencyTableViewCell(currency)
return cell
case 1:
let cell = SettingsServerTableViewCell()
return cell
case 2:
let cell = SettingsTransactionsNotificationTableViewCell(style: .default, reuseIdentifier: "transactions")
return cell
case 3:
let cell = SettingsDelegateNotifcationTableViewCell(style: .default, reuseIdentifier: "delegate")
return cell
default:
let cell = SettingsLogoutTableViewCell(style: .default, reuseIdentifier: "logout")
return cell
}
}
}
|
216609e9d703b92fd1ce037c7be33207
| 36.008 | 137 | 0.669909 | false | false | false | false |
mukeshthawani/TriLabelView
|
refs/heads/master
|
Demo-iOS/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Demo-iOS
//
// Created by Mukesh Thawani on 10/07/16.
// Copyright © 2016 Mukesh Thawani. All rights reserved.
//
import UIKit
import TriLabelView
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
private var colorList:[UIColor] = [.cyan,.cyan,.gray,.gray, .purple, .purple]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: "cell")
collectionView.backgroundColor = UIColor.white
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let viewWidth = view.frame.width
let viewHeight = view.frame.height
let cellSize = CGSize(width: viewWidth/2, height: viewHeight/3)
return cellSize
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell
let cellTriLabel = cell.triLabel!
// Length Percentage
cellTriLabel.lengthPercentage = 50
// Text
cellTriLabel.labelText = "NEW"
// Text Color
cellTriLabel.textColor = UIColor.white
// Font
cellTriLabel.labelFont = UIFont(name: "HelveticaNeue-Bold", size: 19)!
// Background Color
cellTriLabel.viewColor = UIColor.brown
switch indexPath.row {
case 0:
cellTriLabel.position = .TopLeft
case 1:
cellTriLabel.position = .TopRight
case 2:
cellTriLabel.position = .BottomLeft
case 3:
cellTriLabel.position = .BottomRight
default:
cellTriLabel.isHidden = true
break
}
cell.backgroundColor = colorList[indexPath.row]
return cell
}
}
|
91bd3317e7db27e06d1de0583266222e
| 32.375 | 121 | 0.635581 | false | false | false | false |
naru-jpn/pencil
|
refs/heads/master
|
PencilTests/UIntSpec.swift
|
mit
|
1
|
//
// UIntSpec.swift
// Pencil
//
// Created by naru on 2016/10/17.
// Copyright © 2016年 naru. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Pencil
class UIntSpec: QuickSpec {
override func spec() {
describe("UInt") {
context("for some value") {
it("can be encode/decode") {
let num: UInt = 5
let data: Data = num.data
expect(UInt.value(from: data)).to(equal(num))
}
}
context("for zero") {
it("can be encode/decode") {
let num: UInt = 0
let data: Data = num.data
expect(UInt.value(from: data)).to(equal(num))
}
}
context("for max") {
it("can be encode/decode") {
let num: UInt = UInt.max
let data: Data = num.data
expect(UInt.value(from: data)).to(equal(num))
}
}
context("for min") {
it("can be encode/decode") {
let num: UInt = UInt.min
let data: Data = num.data
expect(UInt.value(from: data)).to(equal(num))
}
}
}
describe("UInt8") {
context("for some value") {
it("can be encode/decode") {
let num: UInt8 = 5
let data: Data = num.data
expect(UInt8.value(from: data)).to(equal(num))
}
}
context("for zero") {
it("can be encode/decode") {
let num: UInt8 = 0
let data: Data = num.data
expect(UInt8.value(from: data)).to(equal(num))
}
}
context("for max") {
it("can be encode/decode") {
let num: UInt8 = UInt8.max
let data: Data = num.data
expect(UInt8.value(from: data)).to(equal(num))
}
}
context("for min") {
it("can be encode/decode") {
let num: UInt8 = UInt8.min
let data: Data = num.data
expect(UInt8.value(from: data)).to(equal(num))
}
}
}
describe("UInt16") {
context("for some value") {
it("can be encode/decode") {
let num: UInt16 = 5
let data: Data = num.data
expect(UInt16.value(from: data)).to(equal(num))
}
}
context("for zero") {
it("can be encode/decode") {
let num: UInt16 = 0
let data: Data = num.data
expect(UInt16.value(from: data)).to(equal(num))
}
}
context("for max") {
it("can be encode/decode") {
let num: UInt16 = UInt16.max
let data: Data = num.data
expect(UInt16.value(from: data)).to(equal(num))
}
}
context("for min") {
it("can be encode/decode") {
let num: UInt16 = UInt16.min
let data: Data = num.data
expect(UInt16.value(from: data)).to(equal(num))
}
}
}
describe("UInt32") {
context("for some value") {
it("can be encode/decode") {
let num: UInt32 = 5
let data: Data = num.data
expect(UInt32.value(from: data)).to(equal(num))
}
}
context("for zero") {
it("can be encode/decode") {
let num: UInt32 = 0
let data: Data = num.data
expect(UInt32.value(from: data)).to(equal(num))
}
}
context("for max") {
it("can be encode/decode") {
let num: UInt32 = UInt32.max
let data: Data = num.data
expect(UInt32.value(from: data)).to(equal(num))
}
}
context("for min") {
it("can be encode/decode") {
let num: UInt32 = UInt32.min
let data: Data = num.data
expect(UInt32.value(from: data)).to(equal(num))
}
}
}
describe("UInt64") {
context("for some value") {
it("can be encode/decode") {
let num: UInt64 = 5
let data: Data = num.data
expect(UInt64.value(from: data)).to(equal(num))
}
}
context("for zero") {
it("can be encode/decode") {
let num: UInt64 = 0
let data: Data = num.data
expect(UInt64.value(from: data)).to(equal(num))
}
}
context("for max") {
it("can be encode/decode") {
let num: UInt64 = UInt64.max
let data: Data = num.data
expect(UInt64.value(from: data)).to(equal(num))
}
}
context("for min") {
it("can be encode/decode") {
let num: UInt64 = UInt64.min
let data: Data = num.data
expect(UInt64.value(from: data)).to(equal(num))
}
}
}
}
}
|
a4da700e947a7b667489de8306350dda
| 30.649485 | 67 | 0.372313 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Legacy/Neocom/Neocom/TrainingQueue.swift
|
lgpl-2.1
|
2
|
//
// TrainingQueue.swift
// Neocom
//
// Created by Artem Shimanski on 21.08.2018.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
class TrainingQueue {
struct Item: Hashable {
let skill: Character.Skill
let targetLevel: Int
let startSP: Int
let finishSP: Int
}
let character: Character
var queue: [Item] = []
init(character: Character) {
self.character = character
}
func add(_ skillType: SDEInvType, level: Int) {
guard let skill = Character.Skill(type: skillType) else {return}
addRequiredSkills(for: skillType)
let typeID = Int(skillType.typeID)
let trainedLevel = character.trainedSkills[typeID]?.trainedSkillLevel ?? 0
guard trainedLevel < level else {return}
let queuedLevels = IndexSet(queue.filter({$0.skill.typeID == typeID}).map{$0.targetLevel})
for i in (trainedLevel + 1)...level {
if !queuedLevels.contains(i) {
let sp = character.skillQueue.first(where: {$0.skill.typeID == skill.typeID && $0.queuedSkill.finishedLevel == i})?.skillPoints
queue.append(Item(skill: skill, targetLevel: i, startSP: sp))
}
}
}
func add(_ mastery: SDECertMastery) {
mastery.skills?.forEach {
guard let skill = $0 as? SDECertSkill else {return}
guard let type = skill.type else {return}
add(type, level: max(Int(skill.skillLevel), 1))
}
}
func addRequiredSkills(for type: SDEInvType) {
type.requiredSkills?.forEach {
guard let requiredSkill = ($0 as? SDEInvTypeRequiredSkill) else {return}
guard let type = requiredSkill.skillType else {return}
add(type, level: Int(requiredSkill.skillLevel))
}
}
func addRequiredSkills(for activity: SDEIndActivity) {
activity.requiredSkills?.forEach {
guard let requiredSkill = ($0 as? SDEIndRequiredSkill) else {return}
guard let type = requiredSkill.skillType else {return}
add(type, level: Int(requiredSkill.skillLevel))
}
}
func remove(_ item: TrainingQueue.Item) {
let indexes = IndexSet(queue.enumerated().filter {$0.element.skill.typeID == item.skill.typeID && $0.element.targetLevel >= item.targetLevel}.map{$0.offset})
indexes.reversed().forEach {queue.remove(at: $0)}
indexes.rangeView.reversed().forEach { queue.removeSubrange($0) }
}
func trainingTime() -> TimeInterval {
return trainingTime(with: character.attributes)
}
func trainingTime(with attributes: Character.Attributes) -> TimeInterval {
return queue.map {$0.trainingTime(with: attributes)}.reduce(0, +)
}
}
extension TrainingQueue.Item {
init(skill: Character.Skill, targetLevel: Int, startSP: Int?) {
self.skill = skill
self.targetLevel = targetLevel
let finishSP = skill.skillPoints(at: targetLevel)
self.startSP = min(startSP ?? skill.skillPoints(at: targetLevel - 1), finishSP)
self.finishSP = finishSP
}
func trainingTime(with attributes: Character.Attributes) -> TimeInterval {
return Double(finishSP - startSP) / skill.skillPointsPerSecond(with: attributes)
}
}
|
4e68af401a6d508db886c933959a52d6
| 29.525773 | 159 | 0.715299 | false | false | false | false |
kylef/JSONSchema.swift
|
refs/heads/master
|
Sources/Validation/pattern.swift
|
bsd-3-clause
|
1
|
import Foundation
func pattern(context: Context, pattern: Any, instance: Any, schema: [String: Any]) -> AnySequence<ValidationError> {
guard let pattern = pattern as? String else {
return AnySequence(EmptyCollection())
}
guard let instance = instance as? String else {
return AnySequence(EmptyCollection())
}
guard let expression = try? NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0)) else {
return AnySequence([
ValidationError(
"[Schema] Regex pattern '\(pattern)' is not valid",
instanceLocation: context.instanceLocation,
keywordLocation: context.keywordLocation
)
])
}
let range = NSMakeRange(0, instance.count)
if expression.matches(in: instance, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range).count == 0 {
return AnySequence([
ValidationError(
"'\(instance)' does not match pattern: '\(pattern)'",
instanceLocation: context.instanceLocation,
keywordLocation: context.keywordLocation
)
])
}
return AnySequence(EmptyCollection())
}
|
e884f9c699863a373a7646186bb5a1cb
| 31.171429 | 125 | 0.694494 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
refs/heads/main
|
Swift/logger-rate-limiter.swift
|
mit
|
1
|
class Logger {
private var logging: [String : Int]
init() {
self.logging = [:]
}
func shouldPrintMessage(_ timestamp: Int, _ message: String) -> Bool {
if let lastTime = logging[message] {
if timestamp - lastTime >= 10 {
logging[message] = timestamp
return true
} else {
return false
}
}
logging[message] = timestamp
return true
}
}
/**
* Your Logger object will be instantiated and called as such:
* let obj = Logger()
* let ret_1: Bool = obj.shouldPrintMessage(timestamp, message)
*/
|
696a20513afbaee82559301b3b6f01d5
| 22.777778 | 74 | 0.531153 | false | false | false | false |
Sharelink/Bahamut
|
refs/heads/master
|
Bahamut/UrlShareContent.swift
|
mit
|
1
|
//
// UrlShareContent.swift
// Bahamut
//
// Created by AlexChow on 15/11/30.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
import EVReflection
class UrlContentView:UIView
{
var model:UrlContentModel!
var titleLable:UILabel!
var linkImg:UIImageView!
private func initViews()
{
if titleLable == nil
{
self.backgroundColor = UIColor.headerColor
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UrlContentView.onTapTitleLable(_:))))
titleLable = UILabel()
titleLable.textAlignment = .Left
titleLable.numberOfLines = 2
titleLable.font = UIFont(name: "System", size: 13)
titleLable.backgroundColor = UIColor.clearColor()
titleLable.textColor = UIColor.lightGrayColor()
self.layer.cornerRadius = 7
self.addSubview(titleLable)
}
if linkImg == nil
{
linkImg = UIImageView(image: UIImage.namedImageInSharelink( "linkIcon"))
linkImg.userInteractionEnabled = true
self.addSubview(linkImg)
}
}
func refresh()
{
initViews()
linkImg.frame = CGRectMake(3, 3, 42, 42)
if String.isNullOrWhiteSpace(model.title)
{
titleLable.text = "EMPTY_TITLE".localizedString()
}else
{
titleLable.text = "\(model.title)"
}
titleLable.frame = CGRectMake(49, 0, self.bounds.width - 49, 48)
}
func onTapTitleLable(ges:UITapGestureRecognizer)
{
if let a = ges.view
{
a.animationMaxToMin(0.1, maxScale: 1.1, completion: { () -> Void in
if let navc = UIApplication.currentNavigationController
{
SimpleBrowser.openUrlWithShare(navc, url: self.model.url)
}
})
}
}
}
extension SimpleBrowser
{
static func openUrlWithShare(currentViewController: UINavigationController,url:String)
{
let broswer = self.openUrl(currentViewController, url: url)
let btn = UIBarButtonItem(image: UIImage.namedImageInSharelink("share_icon"), style: .Plain, target: broswer, action: #selector(SimpleBrowser.shareUrl(_:)))
broswer.navigationItem.rightBarButtonItem = btn
}
func shareUrl(sender:AnyObject?)
{
let share = ShareThing()
share.shareType = ShareThingType.shareUrl.rawValue
let urlModel = UrlContentModel()
urlModel.url = self.url
share.shareContent = urlModel.toJsonString()
ServiceContainer.getService(ShareService).showNewShareController(self.navigationController!, shareModel: share, isReshare: false)
}
}
class UrlContentModel: EVObject
{
var title:String!
var url:String!
}
class UrlContent:UIShareContentDelegate
{
func initContent(shareCell: UIShareThing, share: ShareThing) {
}
func refresh(sender: UIShareContent, share: ShareThing?) {
if let contentView = sender.contentView as? UrlContentView
{
let model = UrlContentModel(json: share?.shareContent)
contentView.model = model
contentView.refresh()
}
}
func getContentFrame(sender: UIShareThing, share: ShareThing?) -> CGRect {
return CGRectMake(0,0,sender.rootController.view.bounds.width - 23,49)
}
func getContentView(sender: UIShareContent, share: ShareThing?) -> UIView {
let view = UrlContentView(frame: CGRectMake(0,0,sender.shareCell.rootController.view.bounds.width - 23,49))
return view
}
}
|
afa81594b7b4e455f09780985c286fc4
| 29.752066 | 164 | 0.624295 | false | false | false | false |
stripe/stripe-ios
|
refs/heads/master
|
StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/Card/STPCardExpiryInputTextFieldValidator.swift
|
mit
|
1
|
//
// STPCardExpiryInputTextFieldValidator.swift
// StripePaymentsUI
//
// Created by Cameron Sabol on 10/22/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripePayments
import UIKit
class STPCardExpiryInputTextFieldValidator: STPInputTextFieldValidator {
override var defaultErrorMessage: String? {
return String.Localized.your_cards_expiration_date_is_invalid
}
public var expiryStrings: (month: String, year: String)? {
guard let inputValue = inputValue else {
return nil
}
let numericInput = STPNumericStringValidator.sanitizedNumericString(for: inputValue)
let monthString = numericInput.stp_safeSubstring(to: 2)
var yearString = numericInput.stp_safeSubstring(from: 2)
// prepend "20" to ensure we provide a 4 digit year, this is to be consistent with Checkout
if yearString.count == 2 {
let centuryLeadingDigits = Int(
floor(Double(Calendar(identifier: .iso8601).component(.year, from: Date())) / 100)
)
yearString = "\(centuryLeadingDigits)\(yearString)"
}
if monthString.count == 2 && yearString.count == 4 {
return (month: monthString, year: yearString)
} else {
return nil
}
}
override public var inputValue: String? {
didSet {
guard let inputValue = inputValue else {
validationState = .incomplete(description: nil)
return
}
let numericInput = STPNumericStringValidator.sanitizedNumericString(for: inputValue)
let monthString = numericInput.stp_safeSubstring(to: 2)
let yearString = numericInput.stp_safeSubstring(from: 2)
let monthState = STPCardValidator.validationState(forExpirationMonth: monthString)
let yearState = STPCardValidator.validationState(
forExpirationYear: yearString,
inMonth: monthString
)
if monthState == .valid && yearState == .valid {
validationState = .valid(message: nil)
} else if monthState == .invalid && yearState == .invalid {
// TODO: We should be more specific here e.g. "Your card's expiration year is in the past."
validationState = .invalid(errorMessage: defaultErrorMessage)
} else if monthState == .invalid {
validationState = .invalid(
errorMessage: String.Localized.your_cards_expiration_month_is_invalid
)
} else if yearState == .invalid {
validationState = .invalid(
errorMessage: String.Localized.your_cards_expiration_year_is_invalid
)
} else {
validationState = .incomplete(
description: !inputValue.isEmpty
? String.Localized.your_cards_expiration_date_is_incomplete : nil
)
}
}
}
}
|
31304ffec8df9bbb0b34cd8e3e95ec0e
| 37.296296 | 107 | 0.60187 | false | false | false | false |
wwq0327/iOS8Example
|
refs/heads/master
|
Diary/Diary/DiaryLocationHelper.swift
|
apache-2.0
|
1
|
//
// DiaryLocationHelper.swift
// Diary
//
// Created by wyatt on 15/6/14.
// Copyright (c) 2015年 Wanqing Wang. All rights reserved.
//
import CoreLocation
class DiaryLocationHelper: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var currentLocation: CLLocation?
var address: String?
var geocoder = CLGeocoder()
override init() {
super.init()
locationManager.delegate = self
// 位置更新的位移触发条件
locationManager.distanceFilter = kCLDistanceFilterNone
// 精度
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// 如果用户停止移动则停止更新位置
locationManager.pausesLocationUpdatesAutomatically = true
// 指南针触发条件
locationManager.headingFilter = kCLHeadingFilterNone
// 请求位置权限
locationManager.requestWhenInUseAuthorization()
println("Location Right")
// 判断是否有位置权限
if (CLLocationManager.locationServicesEnabled()) {
// 开始更新位置
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locationInfo = locations.last as! CLLocation
// println(locationInfo)
geocoder.reverseGeocodeLocation(locationInfo, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("reverse geodcode fail: \(error.localizedDescription)")
}
if let pm = placemarks.first as? CLPlacemark {
self.address = pm.name
NSNotificationCenter.defaultCenter().postNotificationName("DiaryLocationUpdated", object: self.address)
}
})
}
// 失败则停止定位
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error)
locationManager.stopUpdatingLocation()
}
// func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
// // 位置更新后通过CLGeocoder获取位置描述, 例如广州市
// geocoder.reverseGeocodeLocation(newLocation, completionHandler: { (placemarks, error) -> Void in
// if (error != nil) {
// println("reverse geodcode fail: \(error.localizedDescription)")
// }
// if let pm = placemarks as? [CLPlacemark] {
// if pm.count > 0 {
// var placemark = pm.first
// self.address = placemark?.locality
// NSNotificationCenter.defaultCenter().postNotificationName("DiaryLocationUpdated", object: self.address)
// }
// }
// })
// }
}
|
a318d6e8ed9ad8044e62459fe9192466
| 35 | 142 | 0.623798 | false | false | false | false |
klesh/cnodejs-swift
|
refs/heads/master
|
CNode/Libs/AHWebView.swift
|
apache-2.0
|
1
|
//
// WebContent.swift
// Helloworld
//
// Created by Klesh Wong on 1/11/16.
// Copyright © 2016 Klesh Wong. All rights reserved.
import UIKit
class AHWebView : UIWebView, UIWebViewDelegate {
// 调试用
static var count = 0
var index = 0
// 初始化
override func awakeFromNib() {
index = AHWebView.count++
scrollView.scrollEnabled = false
self.delegate = self
self.addObserver(self, forKeyPath: "scrollView.contentSize", options: NSKeyValueObservingOptions.New, context: nil)
}
var startAt: NSDate?
func webViewDidStartLoad(webView: UIWebView) {
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "forceResize", userInfo: nil, repeats: false)
startAt = NSDate()
}
var finishAt: NSDate?
func webViewDidFinishLoad(webView: UIWebView) {
finishAt = NSDate()
resizeToFit()
}
var forced = false
func forceResize() {
if finishAt == nil {
forced = true
resizeToFit()
}
}
let locker = NSLock();
var reloading = false;
func resizeToFit() {
if reloading {
return
} else {
locker.lock();
if !reloading {
reloading = true;
unsafeResize();
reloading = false;
}
locker.unlock();
}
}
var prevWidth: CGFloat?
var prevHeight: CGFloat?
private func unsafeResize() {
if finishAt == nil && !forced {
return
}
let currWidth = scrollView.contentSize.width
let currHeight = scrollView.contentSize.height
if currWidth == prevWidth && currHeight == prevHeight {
return
}
if let tableView = getTableView() {
let tableCell = getTableCell()
let totalMargin = tableCell.frame.height - frame.height
var f = tableCell.frame
f.size.height = totalMargin + currHeight
tableCell.frame = f
print("#\(index) reload height: \(currHeight) forced: \(forced)")
tableView.reloadData()
}
prevWidth = currWidth
prevHeight = currHeight
}
// 监测 html 的内容长度变化
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
resizeToFit()
}
// 释放
deinit {
self.removeObserver(self, forKeyPath: "scrollView.contentSize")
}
weak var tableView: UITableView?
weak var tableCell: UITableViewCell?
func getTableView() -> UITableView? {
if tableView == nil {
tableView = getClosestSuperView(UITableView)
}
return tableView
}
func getTableCell() -> UITableViewCell {
if tableCell == nil {
tableCell = getClosestSuperView(UITableViewCell)
}
return tableCell!
}
// 在 UIView 树中寻找最近指定类型的 view
func getClosestSuperView<T>(viewType: T.Type) -> T? {
var sv = self.superview
while sv != nil && !(sv is T) {
sv = sv?.superview
}
return sv as? T
}
// 将 html 片段包装到 html 中
func wrapHTMLString(html: String) -> String {
return "<html><head><style> html, body { margin: 0; padding: 0; word-wrap: break-word; font-family: 'Lucida Grande' } img { max-width:100% } </style></head><body>\(html)</body></html>"
}
var html: String?
// 加载 html 片段,这个方法会被多次调用,为避免多次触发 webDidFinishLoad,必须作检测
func loadHTMLAsPageOnce(html: String, baseURL: NSURL?) {
if self.html != html {
self.html = html
loadHTMLString(wrapHTMLString(html), baseURL: baseURL)
}
}
}
|
17321979b5f2c234b670cb11c9d29560
| 26.347222 | 192 | 0.556882 | false | false | false | false |
p0dee/PDAlertView
|
refs/heads/master
|
PDAlertView/NSLayoutConstraintAdditions.swift
|
gpl-2.0
|
1
|
//
// NSLayoutConstraintAdditions.swift
// AlertViewMock
//
// Created by Takeshi Tanaka on 12/23/15.
// Copyright © 2015 Takeshi Tanaka. All rights reserved.
//
import UIKit
extension NSLayoutConstraint {
class func constraintsToFillSuperview(_ targetView: UIView) -> [NSLayoutConstraint] {
guard let superview = targetView.superview else {
assert(false, "targetView must have its superview.")
return []
}
var cstrs = [NSLayoutConstraint]()
cstrs.append(targetView.leadingAnchor.constraint(equalTo: superview.leadingAnchor))
cstrs.append(targetView.topAnchor.constraint(equalTo: superview.topAnchor))
cstrs.append(targetView.trailingAnchor.constraint(equalTo: superview.trailingAnchor))
cstrs.append(targetView.bottomAnchor.constraint(equalTo: superview.bottomAnchor))
return cstrs
}
class func constraintsToFillSuperviewMarginsGuide(_ targetView: UIView) -> [NSLayoutConstraint] {
// 以下じゃダメ。なぜ??
// guard let margin = targetView.superview?.layoutMarginsGuide else {
// assert(false, "targetView must have its superview.")
// return []
// }
// var cstrs = [NSLayoutConstraint]()
// print("margin: \(margin)")
// cstrs.append(targetView.leadingAnchor.constraintEqualToAnchor(margin.leadingAnchor))
// cstrs.append(targetView.topAnchor.constraintEqualToAnchor(margin.topAnchor))
// cstrs.append(targetView.trailingAnchor.constraintEqualToAnchor(margin.trailingAnchor))
// cstrs.append(targetView.bottomAnchor.constraintEqualToAnchor(margin.bottomAnchor))
guard targetView.superview != nil else {
assert(false, "targetView must have its superview.")
return []
}
let views = ["view" : targetView]
let formatHoriz = "H:|-[view]-|"
let formatVert = "V:|-[view]-|"
var cstrs = [NSLayoutConstraint]()
cstrs += NSLayoutConstraint.constraints(withVisualFormat: formatHoriz, options: .directionLeadingToTrailing, metrics: nil, views: views)
cstrs += NSLayoutConstraint.constraints(withVisualFormat: formatVert, options: .directionLeadingToTrailing, metrics: nil, views: views)
return cstrs
}
}
|
14a22a882ae7e00aad49805a158b2a6d
| 45.490196 | 144 | 0.659637 | false | false | false | false |
Antondomashnev/Sourcery
|
refs/heads/master
|
Pods/Yams/Sources/Yams/Constructor.swift
|
mit
|
1
|
//
// Constructor.swift
// Yams
//
// Created by Norio Nomura on 12/21/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
import Foundation
public final class Constructor {
public typealias Map = [Tag.Name: (Node) -> Any?]
public init(_ map: Map) {
methodMap = map
}
public func any(from node: Node) -> Any {
if let method = methodMap[node.tag.name], let result = method(node) {
return result
}
switch node {
case .scalar:
return String._construct(from: node)
case .mapping:
return [AnyHashable: Any]._construct_mapping(from: node)
case .sequence:
return [Any].construct_seq(from: node)
}
}
private let methodMap: Map
}
extension Constructor {
public static let `default` = Constructor(defaultMap)
// We can not write extension of map because that is alias of specialized dictionary
public static let defaultMap: Map = [
// Failsafe Schema
.map: [AnyHashable: Any].construct_mapping,
.str: String.construct,
.seq: [Any].construct_seq,
// JSON Schema
.bool: Bool.construct,
.float: Double.construct,
.null: NSNull.construct,
.int: Int.construct,
// http://yaml.org/type/index.html
.binary: Data.construct,
// .merge is supported in `[AnyHashable: Any].construct`.
.omap: [Any].construct_omap,
.pairs: [Any].construct_pairs,
.set: Set<AnyHashable>.construct_set,
.timestamp: Date.construct
// .value is supported in `String.construct` and `[AnyHashable: Any].construct`.
]
}
// MARK: - ScalarConstructible
public protocol ScalarConstructible {
// We don't use overloading `init?(_ node: Node)`
// because that causes difficulties on using `init` as closure
static func construct(from node: Node) -> Self?
}
extension Bool: ScalarConstructible {
public static func construct(from node: Node) -> Bool? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
switch node.scalar!.string.lowercased() {
case "true", "yes", "on":
return true
case "false", "no", "off":
return false
default:
return nil
}
}
}
extension Data: ScalarConstructible {
public static func construct(from node: Node) -> Data? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
let data = Data(base64Encoded: node.scalar!.string, options: .ignoreUnknownCharacters)
return data
}
}
extension Date: ScalarConstructible {
public static func construct(from node: Node) -> Date? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
let scalar = node.scalar!.string
let range = NSRange(location: 0, length: scalar.utf16.count)
guard let result = timestampPattern.firstMatch(in: scalar, options: [], range: range),
result.range.location != NSNotFound else {
return nil
}
#if os(Linux) || swift(>=4.0)
let components = (1..<result.numberOfRanges).map {
scalar.substring(with: result.range(at: $0))
}
#else
let components = (1..<result.numberOfRanges).map {
scalar.substring(with: result.rangeAt($0))
}
#endif
var datecomponents = DateComponents()
datecomponents.calendar = Calendar(identifier: .gregorian)
datecomponents.year = components[0].flatMap { Int($0) }
datecomponents.month = components[1].flatMap { Int($0) }
datecomponents.day = components[2].flatMap { Int($0) }
datecomponents.hour = components[3].flatMap { Int($0) }
datecomponents.minute = components[4].flatMap { Int($0) }
datecomponents.second = components[5].flatMap { Int($0) }
datecomponents.nanosecond = components[6].flatMap {
let length = $0.characters.count
let nanosecond: Int?
if length < 9 {
nanosecond = Int($0 + String(repeating: "0", count: 9 - length))
} else {
#if swift(>=4.0)
nanosecond = Int($0[..<$0.index($0.startIndex, offsetBy: 9)])
#else
nanosecond = Int($0.substring(to: $0.index($0.startIndex, offsetBy: 9)))
#endif
}
return nanosecond
}
datecomponents.timeZone = {
var seconds = 0
if let hourInSecond = components[9].flatMap({ Int($0) }).map({ $0 * 60 * 60 }) {
seconds += hourInSecond
}
if let minuteInSecond = components[10].flatMap({ Int($0) }).map({ $0 * 60 }) {
seconds += minuteInSecond
}
if components[8] == "-" { // sign
seconds *= -1
}
return TimeZone(secondsFromGMT: seconds)
}()
// Using `DateComponents.date` causes `NSUnimplemented()` crash on Linux at swift-3.0.2-RELEASE
return NSCalendar(identifier: .gregorian)?.date(from: datecomponents)
}
private static let timestampPattern: NSRegularExpression = pattern([
"^([0-9][0-9][0-9][0-9])", // year
"-([0-9][0-9]?)", // month
"-([0-9][0-9]?)", // day
"(?:(?:[Tt]|[ \\t]+)",
"([0-9][0-9]?)", // hour
":([0-9][0-9])", // minute
":([0-9][0-9])", // second
"(?:\\.([0-9]*))?", // fraction
"(?:[ \\t]*(Z|([-+])([0-9][0-9]?)", // tz_sign, tz_hour
"(?::([0-9][0-9]))?))?)?$" // tz_minute
].joined()
)
}
extension Double: ScalarConstructible {
public static func construct(from node: Node) -> Double? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
var scalar = node.scalar!.string
switch scalar {
case ".inf", ".Inf", ".INF", "+.inf", "+.Inf", "+.INF":
return Double.infinity
case "-.inf", "-.Inf", "-.INF":
return -Double.infinity
case ".nan", ".NaN", ".NAN":
return Double.nan
default:
scalar = scalar.replacingOccurrences(of: "_", with: "")
if scalar.contains(":") {
return Double(sexagesimal: scalar)
}
return Double(scalar)
}
}
}
extension Int: ScalarConstructible {
public static func construct(from node: Node) -> Int? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
var scalar = node.scalar!.string
scalar = scalar.replacingOccurrences(of: "_", with: "")
if scalar == "0" {
return 0
}
if scalar.hasPrefix("0x") {
#if swift(>=4.0)
let hexadecimal = scalar[scalar.index(scalar.startIndex, offsetBy: 2)...]
#else
let hexadecimal = scalar.substring(from: scalar.index(scalar.startIndex, offsetBy: 2))
#endif
return Int(hexadecimal, radix: 16)
}
if scalar.hasPrefix("0b") {
#if swift(>=4.0)
let octal = scalar[scalar.index(scalar.startIndex, offsetBy: 2)...]
#else
let octal = scalar.substring(from: scalar.index(scalar.startIndex, offsetBy: 2))
#endif
return Int(octal, radix: 2)
}
if scalar.hasPrefix("0o") {
#if swift(>=4.0)
let octal = scalar[scalar.index(scalar.startIndex, offsetBy: 2)...]
#else
let octal = scalar.substring(from: scalar.index(scalar.startIndex, offsetBy: 2))
#endif
return Int(octal, radix: 8)
}
if scalar.hasPrefix("0") {
#if swift(>=4.0)
let octal = scalar[scalar.index(after: scalar.startIndex)...]
#else
let octal = scalar.substring(from: scalar.index(after: scalar.startIndex))
#endif
return Int(octal, radix: 8)
}
if scalar.contains(":") {
return Int(sexagesimal: scalar)
}
return Int(scalar)
}
}
extension String: ScalarConstructible {
public static func construct(from node: Node) -> String? {
return _construct(from: node)
}
fileprivate static func _construct(from node: Node) -> String {
// This will happen while `Dictionary.flatten_mapping()` if `node.tag.name` was `.value`
if case let .mapping(mapping) = node {
for (key, value) in mapping where key.tag.name == .value {
return _construct(from: value)
}
}
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
return node.scalar!.string
}
}
// MARK: - Types that can't conform to ScalarConstructible
extension NSNull/*: ScalarConstructible*/ {
public static func construct(from node: Node) -> NSNull? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
switch node.scalar!.string {
case "", "~", "null", "Null", "NULL":
return NSNull()
default:
return nil
}
}
}
// MARK: mapping
extension Dictionary {
public static func construct_mapping(from node: Node) -> [AnyHashable: Any]? {
return _construct_mapping(from: node)
}
fileprivate static func _construct_mapping(from node: Node) -> [AnyHashable: Any] {
assert(node.isMapping) // swiftlint:disable:next force_unwrapping
let mapping = flatten_mapping(node).mapping!
var dictionary = [AnyHashable: Any](minimumCapacity: mapping.count)
mapping.forEach {
// TODO: YAML supports keys other than str.
dictionary[String._construct(from: $0.key)] = node.tag.constructor.any(from: $0.value)
}
return dictionary
}
private static func flatten_mapping(_ node: Node) -> Node {
assert(node.isMapping) // swiftlint:disable:next force_unwrapping
let mapping = node.mapping!
var pairs = Array(mapping)
var merge = [(key: Node, value: Node)]()
var index = pairs.startIndex
while index < pairs.count {
let pair = pairs[index]
if pair.key.tag.name == .merge {
pairs.remove(at: index)
switch pair.value {
case .mapping:
let flattened_node = flatten_mapping(pair.value)
if let mapping = flattened_node.mapping {
merge.append(contentsOf: mapping)
}
case let .sequence(sequence):
let submerge = sequence
.filter { $0.isMapping } // TODO: Should raise error on other than mapping
.flatMap { flatten_mapping($0).mapping }
.reversed()
submerge.forEach {
merge.append(contentsOf: $0)
}
default:
break // TODO: Should raise error on other than mapping or sequence
}
} else if pair.key.tag.name == .value {
pair.key.tag.name = .str
index += 1
} else {
index += 1
}
}
return Node(merge + pairs, node.tag, mapping.style)
}
}
extension Set {
public static func construct_set(from node: Node) -> Set<AnyHashable>? {
// TODO: YAML supports Hashable elements other than str.
assert(node.isMapping) // swiftlint:disable:next force_unwrapping
return Set<AnyHashable>(node.mapping!.map({ String._construct(from: $0.key) as AnyHashable }))
// Explicitly declaring the generic parameter as `<AnyHashable>` above is required,
// because this is inside extension of `Set` and Swift 3.0.2 can't infer the type without that.
}
}
// MARK: sequence
extension Array {
public static func construct_seq(from node: Node) -> [Any] {
// swiftlint:disable:next force_unwrapping
return node.sequence!.map(node.tag.constructor.any)
}
public static func construct_omap(from node: Node) -> [(Any, Any)] {
// Note: we do not check for duplicate keys.
assert(node.isSequence) // swiftlint:disable:next force_unwrapping
return node.sequence!.flatMap { subnode -> (Any, Any)? in
// TODO: Should raise error if subnode is not mapping or mapping.count != 1
guard let (key, value) = subnode.mapping?.first else { return nil }
return (node.tag.constructor.any(from: key), node.tag.constructor.any(from: value))
}
}
public static func construct_pairs(from node: Node) -> [(Any, Any)] {
// Note: we do not check for duplicate keys.
assert(node.isSequence) // swiftlint:disable:next force_unwrapping
return node.sequence!.flatMap { subnode -> (Any, Any)? in
// TODO: Should raise error if subnode is not mapping or mapping.count != 1
guard let (key, value) = subnode.mapping?.first else { return nil }
return (node.tag.constructor.any(from: key), node.tag.constructor.any(from: value))
}
}
}
fileprivate extension String {
func substring(with range: NSRange) -> String? {
guard range.location != NSNotFound else { return nil }
let utf16lowerBound = utf16.index(utf16.startIndex, offsetBy: range.location)
let utf16upperBound = utf16.index(utf16lowerBound, offsetBy: range.length)
guard let lowerBound = utf16lowerBound.samePosition(in: self),
let upperBound = utf16upperBound.samePosition(in: self) else {
fatalError("unreachable")
}
#if swift(>=4.0)
return String(self[lowerBound..<upperBound])
#else
return substring(with: lowerBound..<upperBound)
#endif
}
}
// MARK: - SexagesimalConvertible
fileprivate protocol SexagesimalConvertible: ExpressibleByIntegerLiteral {
init?(_ value: String)
static func * (lhs: Self, rhs: Self) -> Self
static func *= (lhs: inout Self, rhs: Self)
static func += (lhs: inout Self, rhs: Self)
}
extension SexagesimalConvertible {
fileprivate init(sexagesimal value: String) {
self = value.sexagesimal()
}
}
extension Double: SexagesimalConvertible {}
extension Int: SexagesimalConvertible {
fileprivate init?(_ value: String) {
self.init(value, radix: 10)
}
}
fileprivate extension String {
func sexagesimal<T>() -> T where T: SexagesimalConvertible {
assert(contains(":"))
var scalar = self
var sign: T = 1
if scalar.hasPrefix("-") {
sign = -1
#if swift(>=4.0)
scalar = String(scalar[scalar.index(after: scalar.startIndex)...])
#else
scalar = scalar.substring(from: scalar.index(after: scalar.startIndex))
#endif
} else if scalar.hasPrefix("+") {
#if swift(>=4.0)
scalar = String(scalar[scalar.index(after: scalar.startIndex)...])
#else
scalar = scalar.substring(from: scalar.index(after: scalar.startIndex))
#endif
}
let digits = scalar.components(separatedBy: ":").flatMap({ T($0) }).reversed()
var base: T = 1
var value: T = 0
digits.forEach {
value += $0 * base
base *= 60
}
return sign * value
}
}
|
c59dc7ae07d060022e08afcc43393475
| 35.581948 | 103 | 0.574638 | false | false | false | false |
Bauer312/ProjectEuler
|
refs/heads/master
|
Sources/Problem/Problem4.swift
|
mit
|
1
|
import pal
public class Problem4 : Problem {
public var name: String
public var text: String
public var url: String
private(set) public var answer: String
public func solve() {
let palindromicProducts = maxPalindromicProduct(3)
answer = "\(palindromicProducts[2]), which is the product of \(palindromicProducts[0]) and \(palindromicProducts[1])"
}
public init () {
name = "Problem 4"
text = "Find the largest palindrome made from the product of two 3-digit numbers."
url = "https://projecteuler.net/problem=4"
answer = "Not yet solved."
}
}
|
eaee5412d70160f4dc5de17df8dece03
| 28.2 | 121 | 0.691781 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS
|
refs/heads/master
|
Mr-Ride-iOS/Mr-Ride-iOS/HomePageViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Mr-Ride-iOS
//
// Created by Derek on 5/23/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import UIKit
import Charts
class HomePageViewController: UIViewController, TrackingDelegate, ChartViewDelegate {
@IBOutlet weak var btnSideMenu: UIBarButtonItem!
@IBOutlet weak var btnLetsRide: UIButton!
@IBOutlet weak var labelTotalDistance: UILabel!
@IBOutlet weak var labelTotalCount: UILabel!
@IBOutlet weak var labelAverageSpeed: UILabel!
@IBOutlet weak var chartView: LineChartView!
var totalDistance = 0.0
var totalRun = 0
var avgSpeed = 0.0
var chartDataDistance = [Double]()
var chartDataDate = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setupBackground()
setupNavigationItem()
setupRevealViewController()
setupData()
setupLabels()
setupButton()
setupChartView()
TrackingActionHelper.getInstance().trackingAction(viewName: "home", action: "view_in_home")
}
func setupData() {
chartDataDistance = [Double]()
chartDataDate = [String]()
if LocationRecorder.getInstance().fetchData() != nil {
let allRecord = LocationRecorder.getInstance().fetchData()!
totalRun = allRecord.count
for data in allRecord {
totalDistance = totalDistance + Double(data.distance!)
if chartDataDistance.count > 49 {
chartDataDistance.removeFirst()
chartDataDate.removeFirst()
}
chartDataDistance.append(Double(data.distance!))
// NSDateFormatter.stringFromDate(run.timestamp!)
chartDataDate.append("2016.1.1")
}
setChart(chartDataDate, values: chartDataDistance)
// setChart(allRecord, values: )
totalDistance = totalDistance / 1000
avgSpeed = totalDistance / Double(totalRun)
}
}
func setupBackground() {
let layer = CALayer()
layer.frame = view.bounds
layer.backgroundColor = UIColor.mrLightblueColor().CGColor
// layer.opacity = 1.0
// layer.hidden = false
view.layer.insertSublayer(layer, atIndex: 0)
}
func setupNavigationItem() {
let iconBike = UIImage(named: "icon-bike")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
navigationItem.titleView = UIImageView(image: iconBike)
navigationItem.titleView?.tintColor = UIColor.whiteColor()
btnSideMenu.tintColor = UIColor.whiteColor()
// let navigationvar shadow gone
let shadowImg = UIImage()
navigationController?.navigationBar.shadowImage = shadowImg
navigationController?.navigationBar.setBackgroundImage(shadowImg, forBarMetrics: UIBarMetrics.Default)
}
func setupLabels() {
labelTotalDistance.layer.shadowColor = UIColor.mrDarkSlateBlueColor().CGColor
labelTotalDistance.layer.shadowRadius = 1.0
labelTotalDistance.layer.shadowOpacity = 0.5
labelTotalDistance.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
labelTotalDistance.text = String(format: "%.1f km", totalDistance)
labelTotalCount.text = String(totalRun)
labelAverageSpeed.text = String(format: "%.1f km/h", avgSpeed)
}
func setupButton() {
btnLetsRide.layer.cornerRadius = 30
btnLetsRide.layer.shadowColor = UIColor.mrDarkSlateBlueColor().CGColor
btnLetsRide.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
btnLetsRide.layer.shadowRadius = 1.0
btnLetsRide.layer.shadowOpacity = 0.5
btnLetsRide.tintColor = UIColor.mrWaterBlueColor()
btnLetsRide.addTarget(self, action: #selector(toTrackingPage), forControlEvents: UIControlEvents.TouchUpInside)
}
func toTrackingPage() {
let trackingViewController = storyboard?.instantiateViewControllerWithIdentifier("TrackingViewController") as! TrackingViewController
let NaiVC = UINavigationController(rootViewController: trackingViewController)
NaiVC.modalPresentationStyle = .OverCurrentContext
trackingViewController.dismissDelegate = self
for subview in view.subviews where subview is UILabel { subview.hidden = true }
presentViewController(NaiVC, animated: true, completion: nil)
TrackingActionHelper.getInstance().trackingAction(viewName: "home", action: "select_ride_in_home")
}
func setupRevealViewController() {
btnSideMenu.target = self.revealViewController()
btnSideMenu.action = #selector(SWRevealViewController.revealToggle(_:))
view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
TrackingActionHelper.getInstance().trackingAction(viewName: "home", action: "select_menu_in_home")
}
func setupChartView() {
chartView.backgroundColor = UIColor.mrLightblueColor()
chartView.userInteractionEnabled = false
chartView.delegate = self
chartView.dragEnabled = false
chartView.setScaleEnabled(false)
chartView.pinchZoomEnabled = false
chartView.drawGridBackgroundEnabled = false
chartView.rightAxis.enabled = false
chartView.leftAxis.enabled = false
chartView.xAxis.enabled = false
chartView.legend.enabled = false
chartView.minOffset = 0
chartView.descriptionText = ""
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(yVals: dataEntries, label: "")
chartDataSet.mode = .CubicBezier
chartDataSet.cubicIntensity = 0.3
chartDataSet.drawCirclesEnabled = false
chartDataSet.setColor(UIColor.clearColor())
chartDataSet.drawValuesEnabled = false
let color1 = UIColor.mrLightblueColor()
let color2 = UIColor.mrPineGreen50Color()
let gradient = CAGradientLayer()
gradient.frame = chartView.bounds
gradient.colors = [color1.CGColor, color2.CGColor]
chartDataSet.drawFilledEnabled = true
chartDataSet.fillAlpha = 0.5
chartDataSet.fill = ChartFill.fillWithColor(UIColor.mrWaterBlueColor())
let chartData = LineChartData(xVals: dataPoints, dataSet: chartDataSet)
chartView.data = chartData
}
// TrackingDelegate
func dismissVC() {
// after presented viewcontroller dismissed
for subview in view.subviews where subview is UILabel { subview.hidden = false }
setupData()
setupLabels()
setupChartView()
}
}
|
5091cafd26d3c12ee32278d09ba28209
| 36.443878 | 141 | 0.655266 | false | false | false | false |
steelwheels/Coconut
|
refs/heads/master
|
CoconutData/Source/Value/CNValueSet.swift
|
lgpl-2.1
|
1
|
/*
* @file CNValueSet.swift
* @brief Define CNValueSet class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public class CNValueSet
{
public static let ClassName = "Set"
public static func isSet(dictionary dict: Dictionary<String, CNValue>) -> Bool {
if let clsname = dict["class"] {
switch clsname {
case .stringValue(let str):
return str == CNValueSet.ClassName
default:
break
}
}
return false
}
public static func fromValue(value val: CNValue) -> CNValue? {
if let dict = val.toDictionary() {
return fromValue(value: dict)
} else {
return nil
}
}
public static func fromValue(value val: Dictionary<String, CNValue>) -> CNValue? {
guard CNValue.hasClassName(inValue: val, className: CNValueSet.ClassName) else {
return nil
}
if let vals = val["values"] {
if let srcs = vals.toArray() {
var newarr: Array<CNValue> = []
for elm in srcs {
CNValueSet.insert(target: &newarr, element: elm)
}
return .setValue(newarr)
}
}
return nil
}
public static func toValue(values vals: Array<CNValue>) -> CNValue {
let result: Dictionary<String, CNValue> = [
"class": .stringValue(CNValueSet.ClassName),
"values": .arrayValue(vals)
]
return .dictionaryValue(result)
}
public static func insert(target targ: inout Array<CNValue>, element elm: CNValue) {
let cnt = targ.count
for i in 0..<cnt {
switch CNCompareValue(nativeValue0: elm, nativeValue1: targ[i]) {
case .orderedAscending: // src < mValues
targ.insert(elm, at: i)
return // finish insertions
case .orderedSame: // src == mValues
return // already defined
case .orderedDescending: // mValues[i] < src
break // continue
}
}
targ.append(elm)
}
public static func compare(set0 s0: Array<CNValue>, set1 s1: Array<CNValue>) -> ComparisonResult {
let c0 = s0.count
let c1 = s1.count
if(c0 < c1){
return .orderedAscending
} else if(c0 > c1) {
return .orderedDescending
} else { // c0 == c1
for i in 0..<c0 {
switch CNCompareValue(nativeValue0: s0[i], nativeValue1: s1[i]) {
case .orderedAscending:
return .orderedAscending
case .orderedSame:
break // continue
case .orderedDescending:
return .orderedDescending
}
}
return .orderedSame
}
}
}
|
89fdc1376d06fc23d424f2ddba1272a9
| 23.385417 | 99 | 0.65912 | false | false | false | false |
creisterer-db/Dwifft
|
refs/heads/master
|
Dwifft/TableViewDiffCalculator.swift
|
mit
|
2
|
//
// TableViewDiffCalculator.swift
// Dwifft
//
// Created by Jack Flintermann on 3/13/15.
// Copyright (c) 2015 Places. All rights reserved.
//
import UIKit
public class TableViewDiffCalculator<T: Equatable> {
public weak var tableView: UITableView?
public init(tableView: UITableView, initialRows: [T] = []) {
self.tableView = tableView
self.rows = initialRows
}
/// Right now this only works on a single section of a tableView. If your tableView has multiple sections, though, you can just use multiple TableViewDiffCalculators, one per section, and set this value appropriately on each one.
public var sectionIndex: Int = 0
/// You can change insertion/deletion animations like this! Fade works well. So does Top/Bottom. Left/Right/Middle are a little weird, but hey, do your thing.
public var insertionAnimation = UITableViewRowAnimation.Automatic, deletionAnimation = UITableViewRowAnimation.Automatic
/// Change this value to trigger animations on the table view.
public var rows : [T] {
didSet {
let oldRows = oldValue
let newRows = self.rows
let changes = Diff.calculate(oldRows, newRows)
if (changes.count > 0) {
tableView?.beginUpdates()
let insertionIndexPaths = changes.filter({ $0.isInsertion }).map({ NSIndexPath(forRow: $0.idx, inSection: self.sectionIndex) })
let deletionIndexPaths = changes.filter({ !$0.isInsertion }).map({ NSIndexPath(forRow: $0.idx, inSection: self.sectionIndex) })
tableView?.insertRowsAtIndexPaths(insertionIndexPaths, withRowAnimation: insertionAnimation)
tableView?.deleteRowsAtIndexPaths(deletionIndexPaths, withRowAnimation: deletionAnimation)
tableView?.endUpdates()
}
}
}
}
|
9259e5bfeb563425fca9c42e943b4426
| 39.895833 | 233 | 0.644422 | false | false | false | false |
LamineNdy/SampleApp
|
refs/heads/master
|
SampleApp/Classes/ViewControllers/AlbumTableViewController.swift
|
mit
|
1
|
//
// AlbumTableViewController.swift
// QontoTest
//
// Created by Lamine Ndiaye on 30/11/2016.
// Copyright © 2016 Lamine. All rights reserved.
//
import UIKit
private let albumCellId = "albumCellReuseIdentifier"
private let photoSegue = "photos"
class AlbumTableViewController: UITableViewController {
var albums: [Album]?
var user: User?
override func viewDidLoad() {
super.viewDidLoad()
self.title = user?.userName
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(triggerFetch), for: UIControlEvents.valueChanged)
triggerFetch()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let albums = albums else {
return 0
}
return albums.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let album = albums?[indexPath.row] else {
return UITableViewCell()
}
let cell = tableView.dequeueReusableCell(withIdentifier: albumCellId, for: indexPath)
cell.textLabel?.text = album.title
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == photoSegue {
let vc = segue.destination as? PhotoCollectionViewController
if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) {
let album = self.albums?[indexPath.row]
vc?.album = album
}
}
}
func triggerFetch () {
self.refreshControl?.beginRefreshing()
self.addIndicator()
WebService.fetchAlbums((user?.userId)!) { (albums, error) -> () in
if error == nil {
DispatchQueue.main.async {
self.albums = albums
}
} else {
DispatchQueue.main.async {
self.showAlert(message: "Error")
self.refreshControl?.endRefreshing()
print(error!)
}
}
DispatchQueue.main.async {
self.removeIndicator()
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
}
}
|
8ea93b47d46b5a784f855a55656e37f8
| 26.94382 | 108 | 0.666265 | false | false | false | false |
ecwineland/Presente
|
refs/heads/master
|
Presente/CustomLogInViewController.swift
|
mit
|
1
|
//
// CustomLogInViewController.swift
// Presente
//
// Created by Evan Wineland on 10/13/15.
// Copyright © 2015 Evan Wineland. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class CustomLogInViewController: UIViewController {
@IBOutlet var loginTitle: UILabel!
@IBOutlet var usernameField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var loginButton: UIButton!
@IBOutlet var signUpButton: UIButton!
var actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
override func viewDidLoad() {
super.viewDidLoad()
// Customization for the view
let cornerRadiusVal: CGFloat = 5.0
self.view.backgroundColor = UIColor(red: (52/255.0), green:(57/255.0), blue:(56/255.0), alpha: 1)
loginTitle.textColor = UIColor(red: (235/255.0), green:(231/255.0), blue:(221/255.0), alpha: 1)
loginButton.backgroundColor = UIColor(red: (30/255.0), green:(170/255.0), blue:(226/255.0), alpha: 1)
loginButton.layer.cornerRadius = cornerRadiusVal
signUpButton.backgroundColor = UIColor.clearColor()
signUpButton.layer.borderWidth = 1.0
signUpButton.layer.borderColor = UIColor(red: (255/255.0), green:(206/255.0), blue:(52/255.0), alpha: 1).CGColor
signUpButton.layer.cornerRadius = cornerRadiusVal
passwordField.secureTextEntry = true
self.actInd.center = self.view.center
self.actInd.hidesWhenStopped = true
self.actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(self.actInd)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: Actions
@IBAction func logInAction(sender: AnyObject) {
let username = self.usernameField.text!
let password = self.passwordField.text!
// Check for minimum username and password length
if (username.characters.count < 4 || password.characters.count < 5) {
let alertController : UIAlertController = UIAlertController(title: "Invalid", message: "Username and password must have at least 4, 5 characters respectively", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
} else { //
self.actInd.startAnimating()
PFUser.logInWithUsernameInBackground(username, password: password, block: { (user, error) -> Void in
self.actInd.stopAnimating()
// Login success or denial logic
if (user != nil) {
// Log in success
dispatch_async(dispatch_get_main_queue()){
// self.presentViewController(alertController, animated: true, completion: nil) // NOTE: self recommended by Xcode
// Create user dashboard view controller
var classesController = self.storyboard!.instantiateViewControllerWithIdentifier("Classes")
// Send to classes dashboard
// self.presentViewController(classesController, animated: true, completion: nil)
self.performSegueWithIdentifier("toClasses", sender: self)
}
} else {
// Log in failure
let alertController : UIAlertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil) // NOTE: self recommended by Xcode
}
})
}
}
@IBAction func signUpAction(sender: AnyObject) {
self.performSegueWithIdentifier("signup", sender: self)
}
// @IBAction func signInAction(sender: AnyObject) {
// self.performSegueWithIdentifier("loggedIn", sender: nil) // TODO: Add custom identifier
// }
}
|
92b07114ef4276fecbeea923e2b1ccdd
| 39.047619 | 195 | 0.610186 | false | false | false | false |
shopgun/shopgun-ios-sdk
|
refs/heads/main
|
Sources/TjekAPI/Utils/ImageURL.swift
|
mit
|
1
|
///
/// Copyright (c) 2020 Tjek. All rights reserved.
///
import Foundation
public struct ImageURL: Equatable, Codable, Hashable {
public var url: URL
public var width: Int
public init(url: URL, width: Int) {
self.url = url
self.width = width
}
}
extension Collection where Element == ImageURL {
public var smallestToLargest: [ImageURL] {
self.sorted(by: { $0.width <= $1.width })
}
public var largestImage: ImageURL? {
smallestToLargest.last
}
public var smallestImage: ImageURL? {
smallestToLargest.first
}
// TODO: Add ability to 'round up' to nearest image: LH - 25 May 2020
/**
Returns the smallest image that is at least as wide as the specified `minWidth`.
If no imageURLs match the criteria (they are all smaller than the specified minWidth), and `fallbackToNearest` is true, this will return the largest possible image.
*/
public func imageURL(widthAtLeast minWidth: Int, fallbackToNearest: Bool) -> ImageURL? {
let urls = smallestToLargest
return urls.first(where: { $0.width >= minWidth }) ?? (fallbackToNearest ? urls.last : nil)
}
/**
Returns the largest imageURL whose width is no more than the specified `maxWidth`.
If no imageURLs match the criteria (they are all bigger than the specified maxWidth), and `fallbackToNearest` is true, this will return the smallest possible image.
*/
public func imageURL(widthNoMoreThan maxWidth: Int, fallbackToNearest: Bool) -> ImageURL? {
let urls = smallestToLargest
return urls.last(where: { $0.width <= maxWidth }) ?? (fallbackToNearest ? urls.first : nil)
}
}
|
b597186da8b6e6cf7b44b91e9a0d2398
| 32.403846 | 169 | 0.65285 | false | false | false | false |
joalbright/Gameboard
|
refs/heads/master
|
Gameboards.playground/Sources/Core/Views/TicTacToeView.swift
|
apache-2.0
|
1
|
import UIKit
public class TicTacToeView: UIView {
public var p: CGFloat = 10
public var lineColor: UIColor = .black
public override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineCap(.round)
context?.setLineJoin(.round)
context?.setLineWidth(2)
lineColor.set()
let w = (rect.width - p * 2) / 3
let h = (rect.height - p * 2) / 3
context?.move(to: CGPoint(x: w + p, y: p))
context?.addLine(to: CGPoint(x: w + p, y: rect.height - p))
context?.move(to: CGPoint(x: w * 2 + p, y: p))
context?.addLine(to: CGPoint(x: w * 2 + p, y: rect.height - p))
context?.move(to: CGPoint(x: p, y: h + p))
context?.addLine(to: CGPoint(x: rect.width - p, y: h + p))
context?.move(to: CGPoint(x: p, y: h * 2 + p))
context?.addLine(to: CGPoint(x: rect.width - p, y: h * 2 + p))
context?.strokePath()
}
}
|
cbd55395236419a168249c23f258f0aa
| 26.157895 | 71 | 0.523256 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Library/ViewModels/PledgeExpandableRewardsHeaderViewModel.swift
|
apache-2.0
|
1
|
import KsApi
import Prelude
import ReactiveSwift
import UIKit
public enum PledgeExpandableRewardsHeaderItem {
case header(PledgeExpandableHeaderRewardCellData)
case reward(PledgeExpandableHeaderRewardCellData)
public var data: PledgeExpandableHeaderRewardCellData {
switch self {
case let .header(data): return data
case let .reward(data): return data
}
}
public var isHeader: Bool {
switch self {
case .header: return true
case .reward: return false
}
}
public var isReward: Bool {
switch self {
case .header: return false
case .reward: return true
}
}
}
public struct PledgeExpandableRewardsHeaderViewData {
public let rewards: [Reward]
public let selectedQuantities: SelectedRewardQuantities
public let projectCountry: Project.Country
public let omitCurrencyCode: Bool
}
public protocol PledgeExpandableRewardsHeaderViewModelInputs {
func configure(with data: PledgeExpandableRewardsHeaderViewData)
func expandButtonTapped()
func viewDidLoad()
}
public protocol PledgeExpandableRewardsHeaderViewModelOutputs {
var loadRewardsIntoDataSource: Signal<[PledgeExpandableRewardsHeaderItem], Never> { get }
var expandRewards: Signal<Bool, Never> { get }
}
public protocol PledgeExpandableRewardsHeaderViewModelType {
var inputs: PledgeExpandableRewardsHeaderViewModelInputs { get }
var outputs: PledgeExpandableRewardsHeaderViewModelOutputs { get }
}
public final class PledgeExpandableRewardsHeaderViewModel: PledgeExpandableRewardsHeaderViewModelType,
PledgeExpandableRewardsHeaderViewModelInputs, PledgeExpandableRewardsHeaderViewModelOutputs {
public init() {
let data = Signal.combineLatest(
self.configureWithRewardsProperty.signal.skipNil(),
self.viewDidLoadProperty.signal
)
.map(first)
let rewards = data.map(\.rewards)
let selectedQuantities = data.map(\.selectedQuantities)
let latestRewardDeliveryDate = rewards.map { rewards in
rewards
.compactMap { $0.estimatedDeliveryOn }
.reduce(0) { accum, value in max(accum, value) }
}
self.expandRewards = self.expandButtonTappedProperty.signal
.scan(false) { current, _ in !current }
let estimatedDeliveryString = latestRewardDeliveryDate.map { date -> String? in
guard date > 0 else { return nil }
let dateString = Format.date(
secondsInUTC: date,
template: DateFormatter.monthYear,
timeZone: UTCTimeZone
)
return Strings.backing_info_estimated_delivery_date(delivery_date: dateString)
}
.skipNil()
let total: Signal<Double, Never> = Signal.combineLatest(
rewards,
selectedQuantities
)
.map { rewards, selectedQuantities in
rewards.reduce(0.0) { total, reward in
let totalForReward = reward.minimum
.multiplyingCurrency(Double(selectedQuantities[reward.id] ?? 0))
return total.addingCurrency(totalForReward)
}
}
self.loadRewardsIntoDataSource = Signal.zip(
data,
selectedQuantities,
estimatedDeliveryString,
total
)
.map(items)
}
private let configureWithRewardsProperty = MutableProperty<PledgeExpandableRewardsHeaderViewData?>(nil)
public func configure(with data: PledgeExpandableRewardsHeaderViewData) {
self.configureWithRewardsProperty.value = data
}
private let expandButtonTappedProperty = MutableProperty(())
public func expandButtonTapped() {
self.expandButtonTappedProperty.value = ()
}
private let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
public let loadRewardsIntoDataSource: Signal<[PledgeExpandableRewardsHeaderItem], Never>
public let expandRewards: Signal<Bool, Never>
public var inputs: PledgeExpandableRewardsHeaderViewModelInputs { return self }
public var outputs: PledgeExpandableRewardsHeaderViewModelOutputs { return self }
}
// MARK: - Functions
private func items(
with data: PledgeExpandableRewardsHeaderViewData,
selectedQuantities: SelectedRewardQuantities,
estimatedDeliveryString: String,
total: Double
) -> [PledgeExpandableRewardsHeaderItem] {
guard let totalAmountAttributedText = attributedHeaderCurrency(
with: data.projectCountry, amount: total, omitUSCurrencyCode: data.omitCurrencyCode
) else { return [] }
let headerItem = PledgeExpandableRewardsHeaderItem.header((
text: estimatedDeliveryString,
amount: totalAmountAttributedText
))
let rewardItems = data.rewards.compactMap { reward -> PledgeExpandableRewardsHeaderItem? in
guard let title = reward.title else { return nil }
let quantity = selectedQuantities[reward.id] ?? 0
let itemString = quantity > 1 ? "\(Format.wholeNumber(quantity)) x \(title)" : title
let amountAttributedText = attributedRewardCurrency(
with: data.projectCountry, amount: reward.minimum, omitUSCurrencyCode: data.omitCurrencyCode
)
return PledgeExpandableRewardsHeaderItem.reward((
text: itemString,
amount: amountAttributedText
))
}
return [headerItem] + rewardItems
}
private func attributedHeaderCurrency(
with projectCountry: Project.Country,
amount: Double,
omitUSCurrencyCode: Bool
) -> NSAttributedString? {
let defaultAttributes = checkoutCurrencyDefaultAttributes()
.withAllValuesFrom([.foregroundColor: UIColor.ksr_support_400])
let superscriptAttributes = checkoutCurrencySuperscriptAttributes()
guard
let attributedCurrency = Format.attributedCurrency(
amount,
country: projectCountry,
omitCurrencyCode: omitUSCurrencyCode,
defaultAttributes: defaultAttributes,
superscriptAttributes: superscriptAttributes,
maximumFractionDigits: 0,
minimumFractionDigits: 0
) else { return nil }
return attributedCurrency
}
private func attributedRewardCurrency(
with projectCountry: Project.Country,
amount: Double,
omitUSCurrencyCode: Bool
) -> NSAttributedString {
let currencyString = Format.currency(
amount,
country: projectCountry,
omitCurrencyCode: omitUSCurrencyCode,
maximumFractionDigits: 0,
minimumFractionDigits: 0
)
return NSAttributedString(
string: currencyString,
attributes: [
.foregroundColor: UIColor.ksr_support_400,
.font: UIFont.ksr_subhead().bolded
]
)
}
|
7fcffe57e1d28645d048208288a4143e
| 29.042453 | 105 | 0.746114 | false | false | false | false |
amraboelela/swift
|
refs/heads/master
|
test/SILGen/opaque_values_silgen_lib.swift
|
apache-2.0
|
12
|
// RUN: %target-swift-emit-silgen -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
protocol EmptyP {}
struct String { var ptr: Builtin.NativeObject }
// Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil hidden [ossa] @$ss21s010______PAndS_casesyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type
// CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum
// CHECK: destroy_value [[EAPPLY]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '$ss21s010______PAndS_casesyyF'
func s010______PAndS_cases() {
_ = PAndSEnum.A
}
// Test emitBuiltinReinterpretCast.
// ---
// CHECK-LABEL: sil hidden [ossa] @$ss21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T,
// CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T
// CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[COPY]] : $T to $U
// CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U
// CHECK: destroy_value [[COPY]] : $T
// CHECK: return [[RET]] : $U
// CHECK-LABEL: } // end sil function '$ss21s020__________bitCast_2toq_x_q_mtr0_lF'
func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U {
return Builtin.reinterpretCast(x)
}
// Test emitBuiltinCastReference
// ---
// CHECK-LABEL: sil hidden [ossa] @$ss21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T, %1 : $@thick U.Type):
// CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T
// CHECK: [[SRC:%.*]] = alloc_stack $T
// CHECK: store [[COPY]] to [init] [[SRC]] : $*T
// CHECK: [[DEST:%.*]] = alloc_stack $U
// CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U
// CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U
// CHECK: dealloc_stack [[DEST]] : $*U
// CHECK: dealloc_stack [[SRC]] : $*T
// CHECK-NOT: destroy_value [[ARG]] : $T
// CHECK: return [[LOAD]] : $U
// CHECK-LABEL: } // end sil function '$ss21s030__________refCast_2toq_x_q_mtr0_lF'
func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
// Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil shared [transparent] [ossa] @$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum {
// CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : $@thin PAndSEnum.Type):
// CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String)
// CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String)
// CHECK: return [[RETVAL]] : $PAndSEnum
// CHECK-LABEL: } // end sil function '$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF'
// CHECK-LABEL: sil shared [transparent] [thunk] [ossa] @$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum {
// CHECK: bb0([[ARG:%.*]] : $@thin PAndSEnum.Type):
// CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum
// CHECK: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$ss6EmptyP_pSSs9PAndSEnumOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed EmptyP, @guaranteed String, @guaranteed @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum) -> @out PAndSEnum
// CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[RETVAL]])
// CHECK: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum
// CHECK-LABEL: } // end sil function '$ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc'
enum PAndSEnum { case A(EmptyP, String) }
|
1e72d18d0fd496d66d52858ac9947d39
| 55.558442 | 267 | 0.628932 | false | false | false | false |
sclark01/Swift_VIPER_Demo
|
refs/heads/master
|
VIPER_Demo/VIPER_Demo/Entities/Person.swift
|
mit
|
1
|
import Foundation
struct Person {
let id: Int
let name: String
let phone: String
let age: String
}
extension Person : Equatable {}
func ==(lhs: Person, rhs: Person) -> Bool {
return
lhs.phone == rhs.phone &&
lhs.name == rhs.name &&
lhs.age == rhs.age
}
|
e41d60ff140d8aefe8f458ff1f06335b
| 16.647059 | 43 | 0.578595 | false | false | false | false |
karwa/swift
|
refs/heads/master
|
test/SourceKit/CodeComplete/complete_member.swift
|
apache-2.0
|
2
|
protocol FooProtocol {
/// fooInstanceVar Aaa.
/// Bbb.
///
/// Ccc.
var fooInstanceVar: Int { get }
typealias FooTypeAlias1
func fooInstanceFunc0() -> Double
func fooInstanceFunc1(_ a: Int) -> Double
subscript(i: Int) -> Double { get }
}
func test1(_ a: FooProtocol) {
a.
}
func testOptional1(_ a: FooProtocol?) {
a.
}
class C {
@available(*, unavailable) func unavail() {}
}
func test_unavail(_ a: C) {
a.
}
class Base {
func foo() {}
}
class Derived: Base {
override func foo() {}
}
func testOverrideUSR() {
Derived().
}
// RUN: %sourcekitd-test -req=complete -pos=15:5 %s -- %s > %t.response
// RUN: diff -u %s.response %t.response
//
// RUN: %sourcekitd-test -req=complete -pos=19:5 %s -- %s | %FileCheck %s -check-prefix=CHECK-OPTIONAL
// RUN: %sourcekitd-test -req=complete.open -pos=19:5 %s -- %s | %FileCheck %s -check-prefix=CHECK-OPTIONAL-OPEN
// CHECK-OPTIONAL: {
// CHECK-OPTIONAL: key.kind: source.lang.swift.decl.function.method.instance,
// CHECK-OPTIONAL: key.name: "fooInstanceFunc0()",
// CHECK-OPTIONAL-LABEL: key.sourcetext: "?.fooInstanceFunc1(<#T##a: Int##Int#>)",
// CHECK-OPTIONAL-NEXT: key.description: "fooInstanceFunc1(a: Int)",
// CHECK-OPTIONAL-NEXT: key.typename: "Double",
// CHECK-OPTIONAL-NEXT: key.context: source.codecompletion.context.thisclass,
// CHECK-OPTIONAL-NEXT: key.num_bytes_to_erase: 1,
// CHECK-OPTIONAL-NEXT: key.associated_usrs: "s:15complete_member11FooProtocolP16fooInstanceFunc1ySdSiF",
// CHECK-OPTIONAL-NEXT: key.modulename: "complete_member"
// CHECK-OPTIONAL-NEXT: },
// RUN: %sourcekitd-test -req=complete.open -pos=19:5 %s -- %s | %FileCheck %s -check-prefix=CHECK-OPTIONAL-OPEN
// CHECK-OPTIONAL-OPEN-NOT: key.description: "fooInstanceFunc1
// CHECK-OPTIONAL-OPEN: key.description: "?.fooInstanceFunc1(a: Int)",
// CHECK-OPTIONAL-OPEN-NOT: key.description: "fooInstanceFunc1
// RUN: %sourcekitd-test -req=complete -pos=27:5 %s -- %s | %FileCheck %s -check-prefix=CHECK-UNAVAIL
// CHECK-UNAVAIL-NOT: key.name: "unavail()",
// RUN: %sourcekitd-test -req=complete -pos=39:15 %s -- %s | %FileCheck %s -check-prefix=CHECK-OVERRIDE_USR
// CHECK-OVERRIDE_USR: {
// CHECK-OVERRIDE_USR: key.kind: source.lang.swift.decl.function.method.instance,
// CHECK-OVERRIDE_USR-NEXT: key.name: "foo()",
// CHECK-OVERRIDE_USR-NEXT: key.sourcetext: "foo()",
// CHECK-OVERRIDE_USR-NEXT: key.description: "foo()",
// CHECK-OVERRIDE_USR-NEXT: key.typename: "Void",
// CHECK-OVERRIDE_USR-NEXT: key.context: source.codecompletion.context.thisclass,
// CHECK-OVERRIDE_USR-NEXT: key.num_bytes_to_erase: 0,
// CHECK-OVERRIDE_USR-NEXT: key.associated_usrs: "s:15complete_member7DerivedC3fooyyF s:15complete_member4BaseC3fooyyF",
// CHECK-OVERRIDE_USR-NEXT: key.modulename: "complete_member"
// CHECK-OVERRIDE_USR-NEXT: }
|
ef830705b17ebe26c78bebba76159c46
| 36.525641 | 124 | 0.667578 | false | true | false | false |
baiyidjp/SwiftWB
|
refs/heads/master
|
SwiftWeibo/SwiftWeibo/Classes/ViewModel(视图模型)/JPStatusViewModel(单条微博的视图模型).swift
|
mit
|
1
|
//
// JPStatusViewModel.swift
// SwiftWeibo
//
// Created by tztddong on 2016/11/29.
// Copyright © 2016年 dongjiangpeng. All rights reserved.
//
import Foundation
/// 单条微博的视图模型
class JPStatusViewModel: CustomStringConvertible {
/// 微博模型
var status: JPStatusesModel
/// 会员图标
var memberImage: UIImage?
/// 昵称颜色
var nameColor: UIColor?
/// 认证图标 -1:没有认证 0:认证用户 2.3.5:企业认证 220:达人
var verifiedImage: UIImage?
/// 转发 评论 赞
var retweetStr: String?
var commentStr: String?
var unlikeStr: String?
/// 来源字符串
var sourceStr: String?
/// 配图大小
var pictureViewSize = CGSize()
/// 如果是被转发的微博 原创微博一定没有图
var picURLs: [JPStatusPicModel]? {
//如果没有被转发微博 返回原创微博的图片
return status.retweeted_status?.pic_urls ?? status.pic_urls
}
/// 被转发微博的文本
// var retweetText: String?
/// 正文的属性(带表情)文本
var originalAttributeText: NSAttributedString?
/// 转发微博的属性文本
var retweetAttributeText: NSAttributedString?
var cellRowHeight: CGFloat = 0
/// 构造函数
/// - Parameter model: 微博模型
init(model: JPStatusesModel) {
self.status = model
/// 会员等级 0-6 common_icon_membership_level1
if (model.user?.mbrank)! > 0 && (model.user?.mbrank)! < 7 {
let imageName = "common_icon_membership_level\(model.user?.mbrank ?? 1)"
self.memberImage = UIImage(named: imageName)
nameColor = UIColor.orange
}else {
nameColor = UIColor.black
}
switch model.user?.verified_type ?? -1 {
case 0:
verifiedImage = UIImage(named: "avatar_vip")
case 2 , 3 , 5:
verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 0:
verifiedImage = UIImage(named: "avatar_grassroot")
default:
break
}
//设置底部bar
retweetStr = countString(count: status.reposts_count, defaultStr: "转发")
commentStr = countString(count: status.comments_count, defaultStr: "评论")
unlikeStr = countString(count: status.attitudes_count, defaultStr: "赞")
//计算图片view的size (有转发的时候使用转发)
pictureViewSize = pictureSize(picCount: picURLs?.count)
//被转发微博的文字
let retweetText = "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":" + (status.retweeted_status?.text ?? "")
// 文字大小
let originalFont = UIFont.systemFont(ofSize: 15)
let retweetFont = UIFont.systemFont(ofSize: 14)
//正文微博属性文本
originalAttributeText = JPEmoticonManager.shared.emoticonString(string: status.text ?? "", font: originalFont)
//转发微博的属性文本
retweetAttributeText = JPEmoticonManager.shared.emoticonString(string: retweetText, font: retweetFont)
//使用正则表达式抽取来源字符串
if ((status.source?.jp_hrefSource()?.text) != nil) {
sourceStr = "来自 " + (status.source?.jp_hrefSource()?.text)!
}else {
sourceStr = ""
}
//MARK: 更新高度
updateCellHeight()
}
var description: String {
return status.description
}
/// 将数字转换为描述结果
///
/// - Parameters:
/// - count: 数字
/// - default: 默认字符串
/// - Returns: 结果
fileprivate func countString(count: Int,defaultStr: String) -> String {
/*
count == 0 默认字符串
count < 10000 实际数值
count >= 10000 xxx万
*/
if count == 0 {
return defaultStr
}
if count < 10000 {
return count.description
}
return String(format: "%.02f万", Double(count)/10000)
}
/// 根据图片的数量 计算配图view的size
///
/// - Parameter picCount: 配图数量
/// - Returns: view的size
fileprivate func pictureSize(picCount: Int?) -> CGSize {
if picCount == 0 || picCount == nil {
return CGSize(width: 0, height: 0)
}
//计算行数
let row = (picCount! - 1) / 3 + 1
//计算高度
let pictureViewHeight = JPStatusPicOutterMargin + CGFloat(row) * JPStatusPictureWidth + CGFloat(row-1)*JPStatusPicIntterMargin
return CGSize(width: JPStatusPictureViewWidth, height: pictureViewHeight)
}
/// 根据已缓存的单张图片更新配图view的尺寸
///
/// - Parameter image: 缓存的单张图片
func updatePicViewSizeWithImage(image: UIImage) {
var size = CGSize(width: image.size.width*2, height: image.size.height*2)
/// 对于图片的过宽和过窄的处理
let maxWidth: CGFloat = ScreenWidth - 2*JPStatusPicOutterMargin
let minWidth: CGFloat = 40
let maxHeight: CGFloat = maxWidth*9/16
if size.width > maxWidth {
size.width = maxWidth
size.height = size.width*image.size.height/image.size.width
}
if size.width < minWidth {
size.width = minWidth
size.height = size.width*image.size.height/image.size.width/4
}
if size.height > maxHeight {
size.height = maxHeight
}
size.height += JPStatusPicOutterMargin
pictureViewSize = size
//MARK: 重新计算行高
updateCellHeight()
}
fileprivate func updateCellHeight() {
/*
原创微博: 顶部视图(12)+间距(12)+头像的高度(34)+间距(12)+正文高度(计算)+配图高度(计算)+间距(12)+底部视图(36)
转发微博: 顶部视图(12)+间距(12)+头像的高度(34)+间距(12)+正文高度(计算)+间距(12)+间距(12)+转发文本高度(计算)+配图高度(计算)+间距(12)+底部视图(36)
*/
//间距/头像/底部视图
let margin: CGFloat = 12
let iconHeight: CGFloat = 34
let bottomHeight: CGFloat = 36
//期望文本size/正文字号/转发字号
let textSize = CGSize(width: ScreenWidth-2*margin, height: CGFloat(MAXFLOAT))
//cell 高度
var cellHeight: CGFloat = 0
//文本顶部的高度
cellHeight = 2*margin + iconHeight + margin
//正文文本的高度
if let text = originalAttributeText {
/// attribute 设置行高不再需要Font
cellHeight += text.boundingRect(with: textSize,
options: .usesLineFragmentOrigin,
context: nil).height+1
}
//判断是否是转发微博
if status.retweeted_status != nil {
cellHeight += 2*margin
//转发文本一定使用retweettext 这个是拼接了@昵称:的
if let rettext = retweetAttributeText {
cellHeight += rettext.boundingRect(with: textSize,
options: .usesLineFragmentOrigin,
context: nil).height+1
}
}
//配图
cellHeight += pictureViewSize.height
//底部
cellHeight += margin + bottomHeight
//使用属性记录
cellRowHeight = cellHeight
}
}
|
ef6ef364e78a03de259a7e8cb203d380
| 28.965812 | 134 | 0.541215 | false | false | false | false |
Cessation/even.tr
|
refs/heads/master
|
eventr/ParseUser.swift
|
apache-2.0
|
1
|
//
// ParseUser.swift
// eventr
//
// Created by Sagar on 3/25/16.
// Copyright © 2016 cessation. All rights reserved.
//
import UIKit
import Parse
class ParseUser: NSObject {
//in order to save memory should we remove the first/last name since this information can taken from facebook every time on login. Email would still be needed as a key.
class func postUser(firstName: String?, lastName: String?, email: String?, profileImage: String?
,withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
let user = PFObject(className: "User")
user["firstName"] = firstName
user["lastName"] = lastName
user["email"] = email
user["events"] = []
user["myevents"] = []
user["details"] = ""
user["profileImage"] = profileImage
user.saveInBackgroundWithBlock(completion)
}
//need to add an addEvent API, so when a user rsvps to going to an event, that event will be added to their events list. As with other changes that can occur
}
|
3646fe1787497860f8f57aa571ee5f64
| 33.580645 | 172 | 0.659515 | false | false | false | false |
maximkhatskevich/MKHSequence
|
refs/heads/master
|
Sources/OperationFlow/New.swift
|
mit
|
2
|
//
// New.swift
// MKHOperationFlow
//
// Created by Maxim Khatskevich on 3/1/17.
// Copyright © 2017 Maxim Khatskevich. All rights reserved.
//
import Foundation
//===
public
extension OFL
{
static
func new(
_ name: String = NSUUID().uuidString,
on targetQueue: OperationQueue = Defaults.targetQueue,
maxRetries: UInt = Defaults.maxRetries
) -> Pending
{
return Pending(name,
on: targetQueue,
maxRetries: maxRetries)
}
}
//=== Alternative ways to start new Flow with default params
public
extension OFL
{
static
func take<Input>(
_ input: Input
) -> FirstConnector<Input>
{
return new().take(input)
}
static
func first<Output>(
_ op: @escaping ManagingOperationNoInput<Output>
) -> Connector<Output>
{
return new().first(op)
}
static
func first<Output>(
_ op: @escaping OperationNoInput<Output>
) -> Connector<Output>
{
return new().first(op)
}
}
|
d6d46560dff17985fed6d1891224b8ec
| 18.105263 | 62 | 0.564738 | false | false | false | false |
uptech/Constraid
|
refs/heads/main
|
Tests/ConstraidTests/CenterWithinMarginsTests.swift
|
mit
|
1
|
@testable import Constraid
import XCTest
// This test is only available on iOS
#if os(iOS)
import UIKit
class CenterWithinMarginsTests: XCTestCase {
func testCenterVerticallyWithinMarginsOffsetDown() {
let viewOne = View()
let viewTwo = View()
viewOne.addSubview(viewTwo)
let proxy = viewOne.constraid.center(verticallyWithinMarginsOf: viewTwo, times: 2.0, offsetBy: 10.0, offsetDirection: .down, priority: Constraid.LayoutPriority(rawValue: 500))
let constraints = proxy.constraintCollection
proxy.activate()
let constraintOne = viewOne.constraints.first!
XCTAssertEqual(constraints, viewOne.constraints)
XCTAssertEqual(constraintOne.isActive, true)
XCTAssertEqual(constraintOne.firstItem as! View, viewOne)
XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.centerY)
XCTAssertEqual(constraintOne.relation, LayoutRelation.equal)
XCTAssertEqual(constraintOne.secondItem as! View, viewTwo)
XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.centerYWithinMargins)
XCTAssertEqual(constraintOne.constant, 10.0)
XCTAssertEqual(constraintOne.multiplier, 2.0)
XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false)
}
func testCenterVerticallyWithinMarginsOffsetUp() {
let viewOne = View()
let viewTwo = View()
viewOne.addSubview(viewTwo)
let proxy = viewOne.constraid.center(verticallyWithinMarginsOf: viewTwo, times: 2.0, offsetBy: 10.0, offsetDirection: .up, priority: Constraid.LayoutPriority(rawValue: 500))
let constraints = proxy.constraintCollection
proxy.activate()
let constraintOne = viewOne.constraints.first!
XCTAssertEqual(constraints, viewOne.constraints)
XCTAssertEqual(constraintOne.isActive, true)
XCTAssertEqual(constraintOne.firstItem as! View, viewOne)
XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.centerY)
XCTAssertEqual(constraintOne.relation, LayoutRelation.equal)
XCTAssertEqual(constraintOne.secondItem as! View, viewTwo)
XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.centerYWithinMargins)
XCTAssertEqual(constraintOne.constant, -10.0)
XCTAssertEqual(constraintOne.multiplier, 2.0)
XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false)
}
func testCenterHorizontallyWithinMarginsOffsetRight() {
let viewOne = View()
let viewTwo = View()
viewOne.addSubview(viewTwo)
let proxy = viewOne.constraid.center(horizontallyWithinMarginsOf: viewTwo, times: 2.0, offsetBy: 10.0, offsetDirection: .right, priority: Constraid.LayoutPriority(rawValue: 500))
let constraints = proxy.constraintCollection
proxy.activate()
let constraintOne = viewOne.constraints.first!
XCTAssertEqual(constraints, viewOne.constraints)
XCTAssertEqual(constraintOne.isActive, true)
XCTAssertEqual(constraintOne.firstItem as! View, viewOne)
XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.centerX)
XCTAssertEqual(constraintOne.relation, LayoutRelation.equal)
XCTAssertEqual(constraintOne.secondItem as! View, viewTwo)
XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.centerXWithinMargins)
XCTAssertEqual(constraintOne.constant, 10.0)
XCTAssertEqual(constraintOne.multiplier, 2.0)
XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false)
}
func testCenterHorizontallyWithinMarginsOffsetLeft() {
let viewOne = View()
let viewTwo = View()
viewOne.addSubview(viewTwo)
let proxy = viewOne.constraid.center(horizontallyWithinMarginsOf: viewTwo, times: 2.0, offsetBy: 10.0, offsetDirection: .left,priority: Constraid.LayoutPriority(rawValue: 500))
let constraints = proxy.constraintCollection
proxy.activate()
let constraintOne = viewOne.constraints.first!
XCTAssertEqual(constraints, viewOne.constraints)
XCTAssertEqual(constraintOne.isActive, true)
XCTAssertEqual(constraintOne.firstItem as! View, viewOne)
XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.centerX)
XCTAssertEqual(constraintOne.relation, LayoutRelation.equal)
XCTAssertEqual(constraintOne.secondItem as! View, viewTwo)
XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.centerXWithinMargins)
XCTAssertEqual(constraintOne.constant, -10.0)
XCTAssertEqual(constraintOne.multiplier, 2.0)
XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false)
}
func testCenterWithinMarginsOffsetDownAndRight() {
let viewOne = View()
let viewTwo = View()
viewOne.addSubview(viewTwo)
let proxy = viewOne.constraid.center(withinMarginsOf: viewTwo, times: 2.0, offsetBy: 10.0, offsetDirection: .downAndRight, priority: Constraid.LayoutPriority(rawValue: 500))
let constraints = proxy.constraintCollection
proxy.activate()
let constraintOne = viewOne.constraints.first!
let constraintTwo = viewOne.constraints.last!
XCTAssertEqual(constraints, viewOne.constraints)
XCTAssertEqual(constraintOne.isActive, true)
XCTAssertEqual(constraintOne.firstItem as! View, viewOne)
XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.centerX)
XCTAssertEqual(constraintOne.relation, LayoutRelation.equal)
XCTAssertEqual(constraintOne.secondItem as! View, viewTwo)
XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.centerXWithinMargins)
XCTAssertEqual(constraintOne.constant, 10.0)
XCTAssertEqual(constraintOne.multiplier, 2.0)
XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(constraintTwo.isActive, true)
XCTAssertEqual(constraintTwo.firstItem as! View, viewOne)
XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.centerY)
XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal)
XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo)
XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.centerYWithinMargins)
XCTAssertEqual(constraintTwo.constant, 10.0)
XCTAssertEqual(constraintTwo.multiplier, 2.0)
XCTAssertEqual(constraintTwo.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false)
}
func testCenterWithinMarginsOffsetUpAndRight() {
let viewOne = View()
let viewTwo = View()
viewOne.addSubview(viewTwo)
let proxy = viewOne.constraid.center(withinMarginsOf: viewTwo, times: 2.0, offsetBy: 10.0, offsetDirection: .upAndLeft, priority: Constraid.LayoutPriority(rawValue: 500))
let constraints = proxy.constraintCollection
proxy.activate()
let constraintOne = viewOne.constraints.first!
let constraintTwo = viewOne.constraints.last!
XCTAssertEqual(constraints, viewOne.constraints)
XCTAssertEqual(constraintOne.isActive, true)
XCTAssertEqual(constraintOne.firstItem as! View, viewOne)
XCTAssertEqual(constraintOne.firstAttribute, LayoutAttribute.centerX)
XCTAssertEqual(constraintOne.relation, LayoutRelation.equal)
XCTAssertEqual(constraintOne.secondItem as! View, viewTwo)
XCTAssertEqual(constraintOne.secondAttribute, LayoutAttribute.centerXWithinMargins)
XCTAssertEqual(constraintOne.constant, -10.0)
XCTAssertEqual(constraintOne.multiplier, 2.0)
XCTAssertEqual(constraintOne.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(constraintTwo.isActive, true)
XCTAssertEqual(constraintTwo.firstItem as! View, viewOne)
XCTAssertEqual(constraintTwo.firstAttribute, LayoutAttribute.centerY)
XCTAssertEqual(constraintTwo.relation, LayoutRelation.equal)
XCTAssertEqual(constraintTwo.secondItem as! View, viewTwo)
XCTAssertEqual(constraintTwo.secondAttribute, LayoutAttribute.centerYWithinMargins)
XCTAssertEqual(constraintTwo.constant, -10.0)
XCTAssertEqual(constraintTwo.multiplier, 2.0)
XCTAssertEqual(constraintTwo.priority, LayoutPriority(rawValue: LayoutPriority.RawValue(500)))
XCTAssertEqual(viewOne.translatesAutoresizingMaskIntoConstraints, false)
}
}
#endif
|
cc8990fc002574e43d4a56c1c8237fb5
| 47.92973 | 186 | 0.74768 | false | true | false | false |
ZhangMingNan/MenSao
|
refs/heads/master
|
MenSao/Class/Common/Table/MingCascadeController.swift
|
apache-2.0
|
1
|
//
// MingCascadeController.swift
// MenSao
//
// Created by 张明楠 on 16/2/2.
// Copyright © 2016年 张明楠. All rights reserved.
//
import UIKit
class MingCascadeController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var selectedIndex = 0
var data:[CascadeModel] = []{
didSet{
self.mainTable?.reloadData()
if let id = self.data.first?.id {
self.mainTable?.selectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: true, scrollPosition: UITableViewScrollPosition.None)
mainCellOnClick(id)
}
}
}
var mainTable:UITableView?
var secondaryTable:UITableView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.mainTable = UITableView(frame:CGRectMake(0, 0, 70, self.view.size().height))
self.mainTable?.separatorStyle = UITableViewCellSeparatorStyle.None
self.mainTable?.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.mainTable!)
self.mainTable?.dataSource = self
self.mainTable?.delegate = self
self.secondaryTable = UITableView(frame:CGRectMake(70, 0,self.view.size().width - CGFloat(70), self.view.size().height))
self.secondaryTable?.separatorStyle = UITableViewCellSeparatorStyle.None
self.secondaryTable?.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.secondaryTable!)
self.secondaryTable?.dataSource = self
self.secondaryTable?.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
self.mainTable?.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
self.secondaryTable?.contentInset = self.mainTable!.contentInset
self.secondaryTable?.rowHeight = secondaryCellHeight()
}
func mainCellOnClick(id:Int){
}
func mainCell()->UITableViewCell{
return MainCell(style: UITableViewCellStyle.Default, reuseIdentifier: "MainCell")
}
func secondaryCellHeight()->CGFloat{
return 44
}
func secondaryTableReload(index:Int){
}
func secondaryCell(sub:SubscribeModel)->UITableViewCell{
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "SecondaryCell")
cell.textLabel?.text = sub.screen_name
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.mainTable {
return data.count
}else if tableView == self.secondaryTable {
if data.count == 0 {
return 0
}else{
secondaryTableReload(selectedIndex)
}
return data[selectedIndex].sub.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.mainTable {
let cell = mainCell()
cell.textLabel?.text = data[indexPath.row].name
return cell
}else if tableView == self.secondaryTable {
let cell = secondaryCell(data[selectedIndex].sub[indexPath.row])
return cell
}
return UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell");
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == self.mainTable {
selectedIndex = indexPath.row
mainCellOnClick(self.data[indexPath.row].id)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
3b8a3c11360f08b5cc1b97d1440ca88e
| 30.075 | 154 | 0.652454 | false | false | false | false |
DarlingXIe/WeiBoProject
|
refs/heads/master
|
WeiBo/WeiBo/Classes/Tools/ThirdLib/SnapKit修改版/ConstraintDescription.swift
|
mit
|
4
|
//
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to expose the final API of a `ConstraintDescription` which allows getting a constraint from it
*/
public protocol ConstraintDescriptionFinalizable: class {
var constraint: Constraint { get }
func labeled(_ label: String) -> ConstraintDescriptionFinalizable
}
/**
Used to expose priority APIs
*/
public protocol ConstraintDescriptionPriortizable: ConstraintDescriptionFinalizable {
func priority(_ priority: Float) -> ConstraintDescriptionFinalizable
func priority(_ priority: Double) -> ConstraintDescriptionFinalizable
func priority(_ priority: CGFloat) -> ConstraintDescriptionFinalizable
func priority(_ priority: UInt) -> ConstraintDescriptionFinalizable
func priority(_ priority: Int) -> ConstraintDescriptionFinalizable
func priorityRequired() -> ConstraintDescriptionFinalizable
func priorityHigh() -> ConstraintDescriptionFinalizable
func priorityMedium() -> ConstraintDescriptionFinalizable
func priorityLow() -> ConstraintDescriptionFinalizable
}
/**
Used to expose multiplier & constant APIs
*/
public protocol ConstraintDescriptionEditable: ConstraintDescriptionPriortizable {
@discardableResult
func multipliedBy(_ amount: Float) -> ConstraintDescriptionEditable
@discardableResult
func multipliedBy(_ amount: Double) -> ConstraintDescriptionEditable
@discardableResult
func multipliedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func multipliedBy(_ amount: Int) -> ConstraintDescriptionEditable
@discardableResult
func multipliedBy(_ amount: UInt) -> ConstraintDescriptionEditable
@discardableResult
func dividedBy(_ amount: Float) -> ConstraintDescriptionEditable
@discardableResult
func dividedBy(_ amount: Double) -> ConstraintDescriptionEditable
@discardableResult
func dividedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func dividedBy(_ amount: Int) -> ConstraintDescriptionEditable
@discardableResult
func dividedBy(_ amount: UInt) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: Float) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: Double) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: Int) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: UInt) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: CGPoint) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: CGSize) -> ConstraintDescriptionEditable
@discardableResult
func offset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable
@discardableResult
func inset(_ amount: Float) -> ConstraintDescriptionEditable
@discardableResult
func inset(_ amount: Double) -> ConstraintDescriptionEditable
@discardableResult
func inset(_ amount: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func inset(_ amount: Int) -> ConstraintDescriptionEditable
@discardableResult
func inset(_ amount: UInt) -> ConstraintDescriptionEditable
@discardableResult
func inset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable
}
/**
Used to expose relation APIs
*/
public protocol ConstraintDescriptionRelatable: class {
@discardableResult
func equalTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: View) -> ConstraintDescriptionEditable
@discardableResult
func equalToSuperview() -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
@discardableResult
func equalTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
@discardableResult
func equalTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: Float) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: Double) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: Int) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: UInt) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: CGSize) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: CGPoint) -> ConstraintDescriptionEditable
@discardableResult
func equalTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualToSuperview() -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
@discardableResult
func lessThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
@discardableResult
func lessThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable
@discardableResult
func lessThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualToSuperview() -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
@discardableResult
func greaterThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
@discardableResult
func greaterThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable
@discardableResult
func greaterThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable
}
/**
Used to expose chaining APIs
*/
public protocol ConstraintDescriptionExtendable: ConstraintDescriptionRelatable {
var left: ConstraintDescriptionExtendable { get }
var top: ConstraintDescriptionExtendable { get }
var bottom: ConstraintDescriptionExtendable { get }
var right: ConstraintDescriptionExtendable { get }
var leading: ConstraintDescriptionExtendable { get }
var trailing: ConstraintDescriptionExtendable { get }
var width: ConstraintDescriptionExtendable { get }
var height: ConstraintDescriptionExtendable { get }
var centerX: ConstraintDescriptionExtendable { get }
var centerY: ConstraintDescriptionExtendable { get }
var baseline: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var firstBaseline: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var leftMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var rightMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var topMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var bottomMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var leadingMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var trailingMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var centerXWithinMargins: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var centerYWithinMargins: ConstraintDescriptionExtendable { get }
}
/**
Used to internally manage building constraint
*/
internal class ConstraintDescription: ConstraintDescriptionExtendable, ConstraintDescriptionEditable, ConstraintDescriptionFinalizable {
internal var left: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Left) }
internal var top: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Top) }
internal var right: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Right) }
internal var bottom: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Bottom) }
internal var leading: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Leading) }
internal var trailing: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Trailing) }
internal var width: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Width) }
internal var height: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Height) }
internal var centerX: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterX) }
internal var centerY: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterY) }
internal var baseline: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Baseline) }
internal var label: String?
@available(iOS 8.0, *)
internal var firstBaseline: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.FirstBaseline) }
@available(iOS 8.0, *)
internal var leftMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.LeftMargin) }
@available(iOS 8.0, *)
internal var rightMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.RightMargin) }
@available(iOS 8.0, *)
internal var topMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.TopMargin) }
@available(iOS 8.0, *)
internal var bottomMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.BottomMargin) }
@available(iOS 8.0, *)
internal var leadingMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.LeadingMargin) }
@available(iOS 8.0, *)
internal var trailingMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.TrailingMargin) }
@available(iOS 8.0, *)
internal var centerXWithinMargins: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterXWithinMargins) }
@available(iOS 8.0, *)
internal var centerYWithinMargins: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterYWithinMargins) }
// MARK: initializer
init(fromItem: ConstraintItem) {
self.fromItem = fromItem
self.toItem = ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
// MARK: equalTo
internal func equalTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalToSuperview() -> ConstraintDescriptionEditable {
guard let superview = fromItem.view?.superview else {
fatalError("equalToSuperview() requires the view have a superview before being set.")
}
return self.equalTo(superview)
}
@available(iOS 7.0, *)
internal func equalTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
@available(iOS 9.0, OSX 10.11, *)
internal func equalTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
// MARK: lessThanOrEqualTo
internal func lessThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualToSuperview() -> ConstraintDescriptionEditable {
guard let superview = fromItem.view?.superview else {
fatalError("lessThanOrEqualToSuperview() requires the view have a superview before being set.")
}
return self.lessThanOrEqualTo(superview)
}
@available(iOS 7.0, *)
internal func lessThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
@available(iOS 9.0, OSX 10.11, *)
internal func lessThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
// MARK: greaterThanOrEqualTo
internal func greaterThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualToSuperview() -> ConstraintDescriptionEditable {
guard let superview = fromItem.view?.superview else {
fatalError("greaterThanOrEqualToSuperview() requires the view have a superview before being set.")
}
return self.greaterThanOrEqualTo(superview)
}
@available(iOS 7.0, *)
internal func greaterThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
@available(iOS 9.0, OSX 10.11, *)
internal func greaterThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
// MARK: multiplier
internal func multipliedBy(_ amount: Float) -> ConstraintDescriptionEditable {
self.multiplier = amount
return self
}
internal func multipliedBy(_ amount: Double) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(_ amount: Int) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(_ amount: UInt) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func dividedBy(_ amount: Float) -> ConstraintDescriptionEditable {
self.multiplier = 1.0 / amount;
return self
}
internal func dividedBy(_ amount: Double) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(_ amount: Int) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(_ amount: UInt) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
// MARK: offset
internal func offset(_ amount: Float) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(_ amount: Double) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: CGFloat) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: Int) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: UInt) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: CGPoint) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(_ amount: CGSize) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
// MARK: inset
internal func inset(_ amount: Float) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: Double) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: CGFloat) -> ConstraintDescriptionEditable {
self.constant = EdgeInsets(top: amount, left: amount, bottom: -amount, right: -amount)
return self
}
internal func inset(_ amount: Int) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: UInt) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
return self
}
// MARK: priority
internal func priority(_ priority: Float) -> ConstraintDescriptionFinalizable {
self.priority = priority
return self
}
internal func priority(_ priority: Double) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priority(_ priority: CGFloat) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
func priority(_ priority: UInt) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priority(_ priority: Int) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priorityRequired() -> ConstraintDescriptionFinalizable {
return self.priority(1000.0)
}
internal func priorityHigh() -> ConstraintDescriptionFinalizable {
return self.priority(750.0)
}
internal func priorityMedium() -> ConstraintDescriptionFinalizable {
#if os(iOS) || os(tvOS)
return self.priority(500.0)
#else
return self.priority(501.0)
#endif
}
internal func priorityLow() -> ConstraintDescriptionFinalizable {
return self.priority(250.0)
}
// MARK: Constraint
internal var constraint: Constraint {
if self.concreteConstraint == nil {
if self.relation == nil {
fatalError("Attempting to create a constraint from a ConstraintDescription before it has been fully chained.")
}
self.concreteConstraint = ConcreteConstraint(
fromItem: self.fromItem,
toItem: self.toItem,
relation: self.relation!,
constant: self.constant,
multiplier: self.multiplier,
priority: self.priority,
label: self.label)
}
return self.concreteConstraint!
}
func labeled(_ label: String) -> ConstraintDescriptionFinalizable {
self.label = label
return self
}
// MARK: Private
fileprivate let fromItem: ConstraintItem
fileprivate var toItem: ConstraintItem {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var relation: ConstraintRelation? {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var constant: Any = Float(0.0) {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var multiplier: Float = 1.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var priority: Float = 1000.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var concreteConstraint: ConcreteConstraint? = nil
fileprivate func addConstraint(_ attributes: ConstraintAttributes) -> ConstraintDescription {
if self.relation == nil {
self.fromItem.attributes += attributes
}
return self
}
fileprivate func constrainTo(_ other: ConstraintItem, relation: ConstraintRelation) -> ConstraintDescription {
if other.attributes != ConstraintAttributes.None {
let toLayoutAttributes = other.attributes.layoutAttributes
if toLayoutAttributes.count > 1 {
let fromLayoutAttributes = self.fromItem.attributes.layoutAttributes
if toLayoutAttributes != fromLayoutAttributes {
NSException(name: NSExceptionName(rawValue: "Invalid Constraint"), reason: "Cannot constrain to multiple non identical attributes", userInfo: nil).raise()
return self
}
other.attributes = ConstraintAttributes.None
}
}
self.toItem = other
self.relation = relation
return self
}
fileprivate func constrainTo(_ other: View, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
@available(iOS 7.0, *)
fileprivate func constrainTo(_ other: LayoutSupport, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
@available(iOS 9.0, OSX 10.11, *)
fileprivate func constrainTo(_ other: NSLayoutAnchor<AnyObject>, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: Float, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: Double, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: CGSize, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: CGPoint, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: EdgeInsets, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
}
|
8964ba3c12bb41708803a37c83dcf428
| 43.98557 | 174 | 0.717723 | false | false | false | false |
Igor-Palaguta/YoutubeEngine
|
refs/heads/master
|
Source/YoutubeEngine/Requests/SearchRequest.swift
|
mit
|
1
|
import Foundation
public enum ContentType: String, RequestParameterRepresenting {
case video
case channel
case playlist
}
public struct SearchRequest {
public enum Filter {
case term(String, [ContentType: [Part]])
case fromChannel(String, [Part])
case relatedTo(String, [Part])
}
public let filter: Filter
public let limit: Int?
public let pageToken: String?
public init(_ filter: Filter, limit: Int? = nil, pageToken: String? = nil) {
self.filter = filter
self.limit = limit
self.pageToken = pageToken
}
var contentTypes: [ContentType] {
if case .term(_, let parts) = filter {
return Array(parts.keys)
}
return [.video]
}
var videoParts: [Part] {
switch filter {
case .term(_, let parts):
return parts[.video] ?? []
case .fromChannel(_, let videoParts):
return videoParts
case .relatedTo(_, let videoParts):
return videoParts
}
}
var channelParts: [Part] {
switch filter {
case .term(_, let parts):
return parts[.channel] ?? []
default:
return []
}
}
var playlistParts: [Part] {
switch filter {
case .term(_, let parts):
return parts[.playlist] ?? []
default:
return []
}
}
var part: Part {
return .snippet
}
}
extension SearchRequest {
public static func search(withTerm term: String,
requiredVideoParts: [Part]? = nil,
requiredChannelParts: [Part]? = nil,
requiredPlaylistParts: [Part]? = nil,
limit: Int? = nil,
pageToken: String? = nil) -> SearchRequest {
var partsByType: [ContentType: [Part]] = [:]
partsByType[.video] = requiredVideoParts
partsByType[.channel] = requiredChannelParts
partsByType[.playlist] = requiredPlaylistParts
return SearchRequest(.term(term, partsByType),
limit: limit,
pageToken: pageToken)
}
public static func videosFromChannel(withID channelID: String,
requiredParts: [Part],
limit: Int? = nil,
pageToken: String? = nil) -> SearchRequest {
return SearchRequest(.fromChannel(channelID, requiredParts),
limit: limit,
pageToken: pageToken)
}
public static func videosRelatedToVideo(withID videoID: String,
requiredParts: [Part],
limit: Int? = nil,
pageToken: String? = nil) -> SearchRequest {
return SearchRequest(.relatedTo(videoID, requiredParts),
limit: limit,
pageToken: pageToken)
}
}
extension SearchRequest: PageRequest {
typealias Item = SearchItem
var method: HTTPMethod { return .GET }
var command: String { return "search" }
var parameters: [String: String] {
var parameters: [String: String] = [
"part": part.requestParameterValue,
"type": contentTypes.requestParameterValue
]
parameters["maxResults"] = limit.map(String.init)
parameters["pageToken"] = pageToken
switch filter {
case .term(let query, _):
parameters["q"] = query
case .fromChannel(let channelID, _):
parameters["channelId"] = channelID
case .relatedTo(let videoID, _):
parameters["videoId"] = videoID
}
return parameters
}
}
|
eb5060e695dadaeed4c9c27c757cf90c
| 29.48062 | 88 | 0.515259 | false | false | false | false |
MagicianDL/Shark
|
refs/heads/master
|
Shark/Views/Home/SKHomeHeaderView.swift
|
mit
|
1
|
//
// SKHomeHeaderView.swift
// Shark
//
// Created by Dalang on 2017/3/5.
// Copyright © 2017年 青岛鲨鱼汇信息技术有限公司. All rights reserved.
//
import UIKit
fileprivate let TAG_HOMEHEADERVIEW_DOWNLOADBUTTON = 100
fileprivate let TAG_HOMEHEADERVIEW_QUESTIONBUTTON = 102
fileprivate let TAG_HOMEHEADERVIEW_SHARKBUTTON = 103
fileprivate let TAG_HOMEHEADERVIEW_TOOLBUTTON = 104
/// 主页的TableHeaderView
final class SKHomeHeaderView: UIView {
// MARK: Properties
// fileprivate lazy var cellInfoArray: [SKCarouselCellInfo] = {
//
// let array: Array = (NSArray(contentsOfFile: Bundle.main.path(forResource: "imageInfos", ofType: "plist")!)! as Array)
//
// var cellInfoArray = [SKCarouselCellInfo]()
//
// for index in 0..<array.count {
// let dic = array[index] as! [String: Any]
// let cellInfo = SKCarouselCellInfo(withDictionary: dic)
// cellInfoArray.append(cellInfo)
// }
//
// return cellInfoArray
// }()
var cellInfoArray: [SKCarouselCellInfo] = [SKCarouselCellInfo]()
fileprivate lazy var carouselView: SKCarouselView = {
let carouselView = SKCarouselView(frame: CGRect.zero, dataSource: self, delegate: self)
return carouselView
} ()
/// 下载按钮
fileprivate lazy var downloadButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_DOWNLOADBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_download"), title: "下载", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 问题按钮
fileprivate lazy var questionButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_QUESTIONBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_question"), title: "问题", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 鲨小白按钮
fileprivate lazy var sharkButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_SHARKBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_shark"), title: "鲨小白", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 工具箱按钮
fileprivate lazy var toolButton: UIButton = {
let button: UIButton = UIButton.init(type: .custom)
button.backgroundColor = UIColor.white
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.tag = TAG_HOMEHEADERVIEW_TOOLBUTTON
button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
button.set(image: UIImage(named: "home_bg_tools"), title: "工具箱", imagePosition: .top, spacing: 10, forState: .normal)
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
} ()
/// 推荐阅读
fileprivate lazy var suggestedReadingView: UIView = {
let baseView: UIView = UIView()
baseView.backgroundColor = UIColor.clear
let view: UIView = UIView()
view.backgroundColor = UIColor.mainBlue
baseView.addSubview(view)
let label: UILabel = UILabel()
label.text = "推荐阅读"
label.textColor = UIColor(hexString: "#666666")
label.font = UIFont.systemFont(ofSize: 16)
label.backgroundColor = UIColor.clear
baseView.addSubview(label)
view.snp.makeConstraints { (maker) in
maker.left.equalTo(baseView.snp.left).offset(8)
maker.height.equalTo(19)
maker.width.equalTo(2)
maker.centerY.equalTo(baseView.snp.centerY)
}
label.snp.makeConstraints { (maker) in
maker.left.equalTo(view.snp.right).offset(8)
maker.top.equalTo(baseView.snp.top)
maker.bottom.equalTo(baseView.snp.bottom)
}
return baseView
} ()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
layout()
}
func reload() {
let array: Array = (NSArray(contentsOfFile: Bundle.main.path(forResource: "imageInfos", ofType: "plist")!)! as Array)
for index in 0..<array.count {
let dic = array[index] as! [String: Any]
let cellInfo = SKCarouselCellInfo(withDictionary: dic)
cellInfoArray.append(cellInfo)
}
carouselView.reloadData()
}
}
// MARK: - Private Method
extension SKHomeHeaderView {
/// 初始化界面
fileprivate func setup() {
self.addSubview(suggestedReadingView)
self.addSubview(downloadButton)
self.addSubview(questionButton)
self.addSubview(sharkButton)
self.addSubview(toolButton)
self.addSubview(carouselView)
}
/// 布局
fileprivate func layout() {
suggestedReadingView.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left)
maker.right.equalTo(self.snp.right)
maker.bottom.equalTo(self.snp.bottom)
maker.height.equalTo(39)
}
downloadButton.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left)
maker.bottom.equalTo(suggestedReadingView.snp.top)
maker.height.equalTo(86)
maker.width.equalTo(self.snp.width).multipliedBy(0.25)
}
questionButton.snp.makeConstraints { (maker) in
maker.left.equalTo(downloadButton.snp.right)
maker.top.equalTo(downloadButton.snp.top)
maker.bottom.equalTo(downloadButton.snp.bottom)
maker.width.equalTo(downloadButton.snp.width)
}
sharkButton.snp.makeConstraints { (maker) in
maker.left.equalTo(questionButton.snp.right)
maker.top.equalTo(downloadButton.snp.top)
maker.bottom.equalTo(downloadButton.snp.bottom)
maker.width.equalTo(downloadButton.snp.width)
}
toolButton.snp.makeConstraints { (maker) in
maker.left.equalTo(sharkButton.snp.right)
maker.top.equalTo(downloadButton.snp.top)
maker.bottom.equalTo(downloadButton.snp.bottom)
maker.width.equalTo(downloadButton.snp.width)
}
carouselView.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left)
maker.right.equalTo(self.snp.right)
maker.bottom.equalTo(downloadButton.snp.top).offset(-5)
maker.height.equalTo(130)
}
}
/// 点击按钮
///
/// - Parameter button: UIButton
@objc fileprivate func buttonPressed(_ button: UIButton) {
}
}
// MARK: - SKCarouselViewDelegate SKCarouselViewDataSource
extension SKHomeHeaderView: SKCarouselViewDelegate, SKCarouselViewDataSource {
func sizeForPage(inCarouselView carouselView: SKCarouselView) -> CGSize {
return CGSize(width: 253, height: 130)
}
func numberOfPages(inCarouselView carouselView: SKCarouselView) -> Int {
return cellInfoArray.count
}
func carouselView(_ carouselView: SKCarouselView, cellForPageAtIndex index: Int) -> SKCarouselCell {
let cell = SKCarouselCellImageView(frame: CGRect(x: 0, y: 0, width: 253 - 4, height: 130))
let cellInfo = cellInfoArray[index]
cell.imageView.image = UIImage(named: cellInfo.imageName)
cell.showTime = TimeInterval(cellInfo.showTime)
return cell
}
func carouselView(_ carouselView: SKCarouselView, didScrollToPage page: Int) {
// print("didScrollToPage \(page)")
}
func carouselView(_ carouselView: SKCarouselView, didSelectPageAtIndex index: Int) {
// print("didSelectPageAtIndex \(index)")
}
}
|
80da9fd475ae55087d032a662dbb6aa1
| 34.623529 | 127 | 0.615808 | false | false | false | false |
wunshine/FoodStyle
|
refs/heads/master
|
FoodStyle/FoodStyle/Classes/Viewcontroller/AccountSetController.swift
|
mit
|
1
|
//
// AccountSetController.swift
// FoodStyle
//
// Created by Woz Wong on 16/3/9.
// Copyright © 2016年 code4Fun. All rights reserved.
//
import UIKit
class AccountSetController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "账号设置"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dissMissVC")
view.backgroundColor = UIColor.lightGrayColor()
}
@objc func dissMissVC(){
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
b5baa99f3e7464aca83267ca9fad00ed
| 32.989011 | 157 | 0.684772 | false | false | false | false |
lelandjansen/fatigue
|
refs/heads/master
|
ios/fatigue/SmartSuggestions.swift
|
apache-2.0
|
1
|
import Foundation
class SmartSuggestions {
init(forQuestionnaireRoot questionnaireRoot: QuestionnaireItem) {
self.questionnaireRoot = questionnaireRoot
self.yesterdayResponse = { () -> QuestionnaireResponse? in
let calendar = NSCalendar.current
let history = QuestionnaireResponse.loadResponses().reversed()
for questionnaireResponse in history {
if calendar.isDateInYesterday(questionnaireResponse.date! as Date) {
return questionnaireResponse
}
else if (questionnaireResponse.date! as Date) < calendar.date(byAdding: .day, value: -1, to: Date())! {
return nil
}
}
return nil
}()
}
let yesterdayResponse: QuestionnaireResponse?
fileprivate let questionnaireRoot: QuestionnaireItem
func makeSmartSuggestion(forQuestion question: Question) -> Question {
switch question.id {
case .sleepInPast48Hours:
return suggestSleepInPast48Hours(forQuestion: question)
case .timeZoneQuantity:
return suggestTimeZoneQuantity(forQuestion: question)
default:
return question
}
}
var dirtyQuestionIds = Set<Questionnaire.QuestionId>()
var previousToday24HoursSleep: Int?
func suggestSleepInPast48Hours(forQuestion question: Question) -> Question {
var smartQuestion = question
smartQuestion.details = String()
guard let today24HoursSleep = Int(selectionForQuestion(withId: .sleepInPast24Hours)!) else {
return question
}
let yesterday24HoursSleep: Int = {
if let yesterdaySelection = yesterdaySelectionForQuestion(withId: .sleepInPast24Hours) {
let sleep = Int(yesterdaySelection)!
smartQuestion.details += "Yesterday: \(sleep) "
smartQuestion.details += (sleep == 1) ? "hr" : "hrs"
smartQuestion.details += "\n"
return sleep
} else {
return Int(QuestionnaireDefaults.sleepInPast24Hours)
}
}()
smartQuestion.details += "Today: \(today24HoursSleep) "
smartQuestion.details += (today24HoursSleep == 1) ? "hr" : "hrs"
smartQuestion.options = Array(today24HoursSleep...48).map{String($0)}
if let today48HoursSleep = Int(question.selection), let previous = previousToday24HoursSleep {
smartQuestion.selection = String(describing: today48HoursSleep + today24HoursSleep - previous)
} else {
smartQuestion.selection = String(describing: yesterday24HoursSleep + today24HoursSleep)
}
previousToday24HoursSleep = today24HoursSleep
return smartQuestion
}
func suggestTimeZoneQuantity(forQuestion question: Question) -> Question {
var smartQuestion = question
smartQuestion.details = String()
if let yesterdaySelection = yesterdaySelectionForQuestion(withId: .timeZoneQuantity) {
smartQuestion.details += "Yesterday: \(yesterdaySelection)"
if !dirtyQuestionIds.contains(.timeZoneQuantity) {
dirtyQuestionIds.insert(.timeZoneQuantity)
smartQuestion.selection = yesterdaySelection
}
}
return smartQuestion
}
func selectionForQuestion(withId id: Questionnaire.QuestionId) -> String? {
var question = questionnaireRoot
while true {
if question is Question && (question as! Question).id == id {
return (question as! Question).selection
}
if let nextItem = question.nextItem {
question.nextItem = nextItem
}
else {
return nil
}
}
}
func yesterdaySelectionForQuestion(withId id: Questionnaire.QuestionId) -> String? {
guard yesterdayResponse != nil else { return nil }
for response in yesterdayResponse!.questionResponses! {
if (response as! QuestionResponse).id == id.rawValue {
return (response as! QuestionResponse).selection
}
}
return nil
}
}
|
55bc601a14cdbea0925e024414e93794
| 39.8 | 119 | 0.61718 | false | false | false | false |
Shvier/Dota2Helper
|
refs/heads/master
|
Dota2Helper/Dota2Helper/Others/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// Dota2Helper
//
// Created by Shvier on 16/8/12.
// Copyright © 2016年 Shvier. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var tabbarVC: UITabBarController?
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
switch shortcutItem.type {
case "OpenNews":
tabbarVC?.selectedViewController = tabbarVC?.viewControllers?[0]
break
case "OpenVideo":
tabbarVC?.selectedViewController = tabbarVC?.viewControllers?[1]
break
case "OpenStrategy":
tabbarVC?.selectedViewController = tabbarVC?.viewControllers?[2]
break
case "OpenUpdate":
tabbarVC?.selectedViewController = tabbarVC?.viewControllers?[3]
break
default:
break
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
tabbarVC = UITabBarController()
let newsVC: DHNewsViewController = DHNewsViewController()
let newsNaVC: UINavigationController = UINavigationController(rootViewController: newsVC)
newsVC.tabBarItem = UITabBarItem(title: "资讯", image: UIImage(named: "tabbar_icon_news")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tabbar_icon_news_h")?.withRenderingMode(.alwaysOriginal))
let videoVC: DHVideoViewController = DHVideoViewController()
let videoNaVC: UINavigationController = UINavigationController(rootViewController: videoVC)
videoVC.tabBarItem = UITabBarItem(title: "视频", image: UIImage(named: "tabbar_icon_video")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tabbar_icon_video_h")?.withRenderingMode(.alwaysOriginal))
let strategyVC: DHStrategyViewController = DHStrategyViewController()
let strategyNaVC: UINavigationController = UINavigationController(rootViewController: strategyVC)
strategyVC.tabBarItem = UITabBarItem(title: "攻略", image: UIImage(named: "tabbar_icon_strategy")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tabbar_icon_strategy_h")?.withRenderingMode(.alwaysOriginal))
let updateVC: DHUpdateViewController = DHUpdateViewController()
let updateNaVC: UINavigationController = UINavigationController(rootViewController: updateVC)
updateVC.tabBarItem = UITabBarItem(title: "更新", image: UIImage(named: "tabbar_icon_update")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tabbar_icon_update_h")?.withRenderingMode(.alwaysOriginal))
let settingsVC: DHSettingsViewController = DHSettingsViewController()
let settingsNaVC: UINavigationController = UINavigationController(rootViewController: settingsVC)
settingsNaVC.tabBarItem = UITabBarItem(title: "其它", image: UIImage(named: "tabbar_icon_settings")?.withRenderingMode(.alwaysOriginal), selectedImage: UIImage(named: "tabbar_icon_settings_h")?.withRenderingMode(.alwaysOriginal))
tabbarVC?.viewControllers = [newsNaVC, videoNaVC, strategyNaVC, updateNaVC, settingsNaVC]
tabbarVC?.tabBar.isTranslucent = false
tabbarVC?.tabBar.barStyle = .black
tabbarVC?.tabBar.tintColor = kTabBarItemColor
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: kThemeColor], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor(red:0.80, green:0.00, blue:0.00, alpha:1.00)], for: .selected)
self.window?.rootViewController = tabbarVC
self.window?.makeKeyAndVisible()
application.setStatusBarHidden(false, with: .fade)
let launchImage: UIImageView = UIImageView(frame: (window?.bounds)!)
launchImage.image = UIImage(named: "launch_image")
window?.addSubview(launchImage)
UIView.animate(withDuration: 1) {
launchImage.alpha = 0.5
UIView.animate(withDuration: 0.7, animations: {
launchImage.bounds = CGRect(x: 0, y: 0, width: 1.5*launchImage.bounds.size.width, height: 1.5*launchImage.bounds.size.height)
launchImage.alpha = 0
})
}
DHLog("Application Launching")
Bugtags.start(withAppKey: BugtagsAppKey, invocationEvent: BTGInvocationEventNone)
NBSAppAgent.start(withAppID: TingyunAppKey)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
|
30aa781dbf84fee991ac7c09530e33ce
| 48.138889 | 235 | 0.697192 | false | false | false | false |
narner/AudioKit
|
refs/heads/master
|
AudioKit/Common/Internals/Microtonality/AKTuningTable+NorthIndianRaga.swift
|
mit
|
1
|
//
// AKTuningTable+NorthIndianRaga.swift
// AudioKit
//
// Created by Marcus W. Hobbs on 4/28/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
extension AKTuningTable {
/// Set tuning to 22 Indian Scale.
/// From Erv Wilson. See http://anaphoria.com/Khiasmos.pdf
@discardableResult public func khiasmos22Indian() -> Int {
let masterSet: [Frequency] = [1 / 1,
256 / 243,
16 / 15,
10 / 9,
9 / 8,
32 / 27,
6 / 5,
5 / 4,
81 / 64,
4 / 3,
27 / 20,
45 / 32,
729 / 512,
3 / 2,
128 / 81,
8 / 5,
5 / 3,
405 / 240,
16 / 9,
9 / 5,
15 / 8,
243 / 128]
_ = tuningTable(fromFrequencies: masterSet)
return masterSet.count
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
static let persianNorthIndianMasterSet: [Frequency] = [1 / 1,
135 / 128,
10 / 9,
9 / 8,
1_215 / 1_024,
5 / 4,
81 / 64,
4 / 3,
45 / 32,
729 / 512,
3 / 2,
405 / 256,
5 / 3,
27 / 16,
16 / 9,
15 / 8,
243 / 128]
fileprivate func helper(_ input: [Int]) -> [Frequency] {
assert(input.count < AKTuningTable.persianNorthIndianMasterSet.count - 1, "internal error: index out of bounds")
let retVal: [Frequency] = input.map({(number: Int) -> Frequency in
return Frequency(AKTuningTable.persianNorthIndianMasterSet[number])
})
return retVal
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian00_17() -> Int {
let h = helper([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian01Kalyan() -> Int {
let h = helper([0, 3, 5, 8, 10, 12, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian02Bilawal() -> Int {
let h = helper([0, 3, 5, 7, 10, 13, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian03Khamaj() -> Int {
let h = helper([0, 3, 5, 7, 10, 12, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian04KafiOld() -> Int {
let h = helper([0, 2, 4, 7, 10, 12, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian05Kafi() -> Int {
let h = helper([0, 3, 4, 7, 10, 13, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian06Asawari() -> Int {
let h = helper([0, 3, 4, 7, 10, 11, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian07Bhairavi() -> Int {
let h = helper([0, 1, 4, 7, 10, 11, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian08Marwa() -> Int {
let h = helper([0, 1, 5, 8, 10, 12, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian09Purvi() -> Int {
let h = helper([0, 1, 5, 8, 10, 11, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian10Lalit2() -> Int {
let h = helper([0, 1, 5, 7, 8, 12, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian11Todi() -> Int {
let h = helper([0, 1, 4, 8, 10, 11, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian12Lalit() -> Int {
let h = helper([0, 1, 5, 7, 8, 11, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian13NoName() -> Int {
let h = helper([0, 1, 4, 8, 10, 11, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian14AnandBhairav() -> Int {
let h = helper([0, 1, 5, 7, 10, 12, 15])
tuningTable(fromFrequencies: h)
return h.count
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian15Bhairav() -> Int {
let h = helper([0, 1, 5, 7, 10, 11, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian16JogiyaTodi() -> Int {
let h = helper([0, 1, 4, 7, 10, 11, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian17Madhubanti() -> Int {
let h = helper([0, 3, 4, 8, 10, 12, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian18NatBhairav() -> Int {
let h = helper([0, 3, 5, 7, 10, 11, 15])
tuningTable(fromFrequencies: h)
return h.count
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian19AhirBhairav() -> Int {
let h = helper([0, 1, 5, 7, 10, 12, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian20ChandraKanada() -> Int {
let h = helper([0, 3, 4, 7, 10, 11, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian21BasantMukhari() -> Int {
let h = helper([0, 1, 5, 7, 10, 11, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian22Champakali() -> Int {
let h = helper([0, 3, 6, 8, 10, 13, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian23Patdeep() -> Int {
let h = helper([0, 3, 4, 7, 10, 13, 15])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian24MohanKauns() -> Int {
let h = helper([0, 3, 5, 7, 10, 11, 14])
return tuningTable(fromFrequencies: h)
}
/// From Erv Wilson. See http://anaphoria.com/genus.pdf
@discardableResult public func presetPersian17NorthIndian25Parameswari() -> Int {
let h = helper([0, 1, 4, 7, 10, 12, 14])
return tuningTable(fromFrequencies: h)
}
}
|
1fecf6826885b4706906eda4fe33a0a5
| 41.216814 | 120 | 0.518185 | false | false | false | false |
GloomySunday049/TMCommon
|
refs/heads/master
|
HandyJsonText/Pods/HandyJSON/HandyJSON/Property.swift
|
apache-2.0
|
3
|
/*
* Copyright 1999-2101 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Created by zhouzhuo on 7/7/16.
//
import Foundation
typealias Byte = Int8
public protocol Property {
}
extension Property {
// locate the head of a struct type object in memory
mutating func headPointerOfStruct() -> UnsafeMutablePointer<Byte> {
return withUnsafeMutablePointer(to: &self) {
return UnsafeMutableRawPointer($0).bindMemory(to: Byte.self, capacity: MemoryLayout<Self>.stride)
}
}
// locating the head of a class type object in memory
mutating func headPointerOfClass() -> UnsafeMutablePointer<Byte> {
let opaquePointer = Unmanaged.passUnretained(self as AnyObject).toOpaque()
let mutableTypedPointer = opaquePointer.bindMemory(to: Byte.self, capacity: MemoryLayout<Self>.stride)
return UnsafeMutablePointer<Byte>(mutableTypedPointer)
}
// memory size occupy by self object
static func size() -> Int {
return MemoryLayout<Self>.size
}
// align
static func align() -> Int {
return MemoryLayout<Self>.alignment
}
// Returns the offset to the next integer that is greater than
// or equal to Value and is a multiple of Align. Align must be
// non-zero.
static func offsetToAlignment(value: Int, align: Int) -> Int {
let m = value % align
return m == 0 ? 0 : (align - m)
}
}
public protocol HandyJSON: Property {
init()
mutating func mapping(mapper: HelpingMapper)
}
public extension HandyJSON {
public mutating func mapping(mapper: HelpingMapper) {}
}
public protocol InitWrapperProtocol {
func convertToEnum(object: NSObject) -> Any?
}
public struct InitWrapper<T: Property>: InitWrapperProtocol {
var _init: ((T) -> Any?)?
public init(rawInit: @escaping ((T) -> Any?)) {
self._init = rawInit
}
public func convertToEnum(object: NSObject) -> Any? {
if let typedValue = T.valueFrom(object: object) {
return _init?(typedValue)
}
return nil
}
}
public protocol HandyJSONEnum: Property {
static func makeInitWrapper() -> InitWrapperProtocol?
}
protocol BasePropertyProtocol: HandyJSON {
}
protocol OptionalTypeProtocol: HandyJSON {
static func optionalFromNSObject(object: NSObject) -> Any?
}
extension Optional: OptionalTypeProtocol {
public init() {
self = nil
}
static func optionalFromNSObject(object: NSObject) -> Any? {
if let value = (Wrapped.self as? Property.Type)?.valueFrom(object: object) as? Wrapped {
return Optional(value)
}
return nil
}
}
protocol ImplicitlyUnwrappedTypeProtocol: HandyJSON {
static func implicitlyUnwrappedOptionalFromNSObject(object: NSObject) -> Any?
}
extension ImplicitlyUnwrappedOptional: ImplicitlyUnwrappedTypeProtocol {
static func implicitlyUnwrappedOptionalFromNSObject(object: NSObject) -> Any? {
if let value = (Wrapped.self as? Property.Type)?.valueFrom(object: object) as? Wrapped {
return ImplicitlyUnwrappedOptional(value)
}
return nil
}
}
protocol ArrayTypeProtocol: HandyJSON {
static func arrayFromNSObject(object: NSObject) -> Any?
}
extension Array: ArrayTypeProtocol {
static func arrayFromNSObject(object: NSObject) -> Any? {
guard let nsArray = object as? NSArray else {
return nil
}
var result: [Element] = [Element]()
nsArray.forEach { (each) in
if let nsObject = each as? NSObject, let element = (Element.self as? Property.Type)?.valueFrom(object: nsObject) as? Element {
result.append(element)
}
}
return result
}
}
protocol DictionaryTypeProtocol: HandyJSON {
static func dictionaryFromNSObject(object: NSObject) -> Any?
}
extension Dictionary: DictionaryTypeProtocol {
static func dictionaryFromNSObject(object: NSObject) -> Any? {
guard let nsDict = object as? NSDictionary else {
return nil
}
var result: [Key: Value] = [Key: Value]()
nsDict.forEach { (key, value) in
if let sKey = key as? Key, let nsValue = value as? NSObject, let nValue = (Value.self as? Property.Type)?.valueFrom(object: nsValue) as? Value {
result[sKey] = nValue
}
}
return result
}
}
extension NSArray: Property {}
extension NSDictionary: Property {}
extension Property {
internal static func _transform(rawData dict: NSDictionary, toPointer pointer: UnsafeMutablePointer<Byte>, toOffset currentOffset: Int, byMirror mirror: Mirror, withMapper mapper: HelpingMapper) -> Int {
var currentOffset = currentOffset
if let superMirror = mirror.superclassMirror {
currentOffset = _transform(rawData: dict, toPointer: pointer, toOffset: currentOffset, byMirror: superMirror, withMapper: mapper)
}
var mutablePointer = pointer.advanced(by: currentOffset)
mirror.children.forEach({ (child) in
var offset = 0, size = 0
guard let propertyType = type(of: child.value) as? Property.Type else {
print("label: ", child.label ?? "", "type: ", "\(type(of: child.value))")
fatalError("Each property should be handyjson-property type")
}
size = propertyType.size()
offset = propertyType.offsetToAlignment(value: currentOffset, align: propertyType.align())
mutablePointer = mutablePointer.advanced(by: offset)
currentOffset += offset
guard let label = child.label else {
mutablePointer = mutablePointer.advanced(by: size)
currentOffset += size
return
}
var key = label
if let converter = mapper.getNameAndConverter(key: mutablePointer.hashValue) {
// if specific key is set, replace the label
if let specifyKey = converter.0 {
key = specifyKey
}
// if specific converter is set, use it the assign value to the property
if let specifyConverter = converter.1 {
let ocValue = (dict[key] as? NSObject)?.toString()
specifyConverter(ocValue ?? "")
mutablePointer = mutablePointer.advanced(by: size)
currentOffset += size
return
}
}
guard let value = dict[key] as? NSObject else {
mutablePointer = mutablePointer.advanced(by: size)
currentOffset += size
return
}
if let sv = propertyType.valueFrom(object: value) {
propertyType.codeIntoMemory(pointer: mutablePointer, value: sv)
}
mutablePointer = mutablePointer.advanced(by: size)
currentOffset += size
})
return currentOffset
}
public static func _transform(dict: NSDictionary, toType type: HandyJSON.Type) -> HandyJSON {
var instance = type.init()
let mirror = Mirror(reflecting: instance)
guard let dStyle = mirror.displayStyle else {
fatalError("Target type must has a display type")
}
var pointer: UnsafeMutablePointer<Byte>!
let mapper = HelpingMapper()
var currentOffset = 0
// do user-specified mapping first
instance.mapping(mapper: mapper)
if dStyle == .class {
pointer = instance.headPointerOfClass()
// for 64bit architecture, it's 16
// for 32bit architecture, it's 12
currentOffset = 8 + MemoryLayout<Int>.size
} else if dStyle == .struct {
pointer = instance.headPointerOfStruct()
} else {
fatalError("Target object must be class or struct")
}
_ = _transform(rawData: dict, toPointer: pointer, toOffset: currentOffset, byMirror: mirror, withMapper: mapper)
return instance
}
static func valueFrom(object: NSObject) -> Self? {
if self is HandyJSONEnum.Type {
if let initWrapper = (self as? HandyJSONEnum.Type)?.makeInitWrapper() {
if let resultValue = initWrapper.convertToEnum(object: object) {
return resultValue as? Self
}
}
return nil
} else if self is BasePropertyProtocol.Type {
// base type can be transformed directly
return baseValueFrom(object: object)
} else if self is OptionalTypeProtocol.Type {
// optional type, we parse the wrapped generic type to construct the value, then wrap it to optional
return (self as! OptionalTypeProtocol.Type).optionalFromNSObject(object: object) as? Self
} else if self is ImplicitlyUnwrappedTypeProtocol.Type {
// similar to optional
return (self as! ImplicitlyUnwrappedTypeProtocol.Type).implicitlyUnwrappedOptionalFromNSObject(object: object) as? Self
} else if self is ArrayTypeProtocol.Type {
// we can't retrieve the generic type wrapped by array here, so we go into array extension to do the casting
return (self as! ArrayTypeProtocol.Type).arrayFromNSObject(object: object) as? Self
} else if self is DictionaryTypeProtocol.Type {
// similar to array
return (self as! DictionaryTypeProtocol.Type).dictionaryFromNSObject(object: object) as? Self
} else if self is NSArray.Type {
if let arr = object as? NSArray {
return arr as? Self
}
} else if self is NSDictionary.Type {
if let dict = object as? NSDictionary {
return dict as? Self
}
} else if self is HandyJSON.Type {
if let dict = object as? NSDictionary {
// nested object, transform recursively
return _transform(dict: dict, toType: self as! HandyJSON.Type) as? Self
}
}
return nil
}
// base type supported parsing directly
static func baseValueFrom(object: NSObject) -> Self? {
switch self {
case is Int8.Type:
return object.toInt8() as? Self
case is UInt8.Type:
return object.toUInt8() as? Self
case is Int16.Type:
return object.toInt16() as? Self
case is UInt16.Type:
return object.toUInt16() as? Self
case is Int32.Type:
return object.toInt32() as? Self
case is UInt32.Type:
return object.toUInt32() as? Self
case is Int64.Type:
return object.toInt64() as? Self
case is UInt64.Type:
return object.toUInt64() as? Self
case is Bool.Type:
return object.toBool() as? Self
case is Int.Type:
return object.toInt() as? Self
case is UInt.Type:
return object.toUInt() as? Self
case is Float.Type:
return object.toFloat() as? Self
case is Double.Type:
return object.toDouble() as? Self
case is String.Type:
return object.toString() as? Self
case is NSString.Type:
return object.toNSString() as? Self
case is NSNumber.Type:
return object.toNSNumber() as? Self
default:
break
}
return nil
}
// keep in mind, self type is the same with type of value
static func codeIntoMemory(pointer: UnsafeMutablePointer<Byte>, value: Property) {
pointer.withMemoryRebound(to: Self.self, capacity: 1, { return $0 }).pointee = value as! Self
}
}
|
920328953e74524538f478105476cfe7
| 32.863014 | 207 | 0.618689 | false | false | false | false |
danthorpe/YapDatabaseExtensions
|
refs/heads/development
|
Pods/YapDatabaseExtensions/YapDatabaseExtensions/Shared/Persistable/Persistable_ObjectWithNoMetadata.swift
|
apache-2.0
|
3
|
//
// Persistable_ObjectWithNoMetadata.swift
// YapDatabaseExtensions
//
// Created by Daniel Thorpe on 11/10/2015.
//
//
import Foundation
import ValueCoding
// MARK: - Persistable
extension Persistable where
Self: NSCoding,
Self.MetadataType == Void {
// Writing
/**
Write the item using an existing transaction.
- parameter transaction: a YapDatabaseReadWriteTransaction
- returns: the receiver.
*/
public func write<WriteTransaction: WriteTransactionType>(transaction: WriteTransaction) -> Self {
return transaction.write(self)
}
/**
Write the item synchronously using a connection.
- parameter connection: a YapDatabaseConnection
- returns: the receiver.
*/
public func write<Connection: ConnectionType>(connection: Connection) -> Self {
return connection.write(self)
}
/**
Write the item asynchronously using a connection.
- parameter connection: a YapDatabaseConnection
- returns: a closure which receives as an argument the receiver of this function.
*/
public func asyncWrite<Connection: ConnectionType>(connection: Connection, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Self -> Void)? = .None) {
return connection.asyncWrite(self, queue: queue, completion: completion)
}
/**
Write the item synchronously using a connection as an NSOperation
- parameter connection: a YapDatabaseConnection
- returns: an `NSOperation`
*/
public func writeOperation<Connection: ConnectionType>(connection: Connection) -> NSOperation {
return NSBlockOperation { connection.write(self) }
}
}
extension SequenceType where
Generator.Element: Persistable,
Generator.Element: NSCoding,
Generator.Element.MetadataType == Void {
/**
Write the items using an existing transaction.
- parameter transaction: a WriteTransactionType e.g. YapDatabaseReadWriteTransaction
- returns: the receiver.
*/
public func write<WriteTransaction: WriteTransactionType>(transaction: WriteTransaction) -> [Generator.Element] {
return transaction.write(self)
}
/**
Write the items synchronously using a connection.
- parameter connection: a ConnectionType e.g. YapDatabaseConnection
- returns: the receiver.
*/
public func write<Connection: ConnectionType>(connection: Connection) -> [Generator.Element] {
return connection.write(self)
}
/**
Write the items asynchronously using a connection.
- parameter connection: a ConnectionType e.g. YapDatabaseConnection
- returns: a closure which receives as an argument the receiver of this function.
*/
public func asyncWrite<Connection: ConnectionType>(connection: Connection, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Generator.Element] -> Void)? = .None) {
return connection.asyncWrite(self, queue: queue, completion: completion)
}
/**
Write the item synchronously using a connection as an NSOperation
- parameter connection: a YapDatabaseConnection
- returns: an `NSOperation`
*/
public func writeOperation<Connection: ConnectionType>(connection: Connection) -> NSOperation {
return NSBlockOperation { connection.write(self) }
}
}
// MARK: - Readable
extension Readable where
ItemType: NSCoding,
ItemType: Persistable,
ItemType.MetadataType == Void {
func inTransaction(transaction: Database.Connection.ReadTransaction, atIndex index: YapDB.Index) -> ItemType? {
return transaction.readAtIndex(index)
}
func inTransactionAtIndex(transaction: Database.Connection.ReadTransaction) -> YapDB.Index -> ItemType? {
return { self.inTransaction(transaction, atIndex: $0) }
}
func atIndexInTransaction(index: YapDB.Index) -> Database.Connection.ReadTransaction -> ItemType? {
return { self.inTransaction($0, atIndex: index) }
}
func atIndexesInTransaction<
Indexes where
Indexes: SequenceType,
Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) -> Database.Connection.ReadTransaction -> [ItemType] {
let atIndex = inTransactionAtIndex
return { indexes.flatMap(atIndex($0)) }
}
func inTransaction(transaction: Database.Connection.ReadTransaction, byKey key: String) -> ItemType? {
return inTransaction(transaction, atIndex: ItemType.indexWithKey(key))
}
func inTransactionByKey(transaction: Database.Connection.ReadTransaction) -> String -> ItemType? {
return { self.inTransaction(transaction, byKey: $0) }
}
func byKeyInTransaction(key: String) -> Database.Connection.ReadTransaction -> ItemType? {
return { self.inTransaction($0, byKey: key) }
}
func byKeysInTransaction(keys: [String]? = .None) -> Database.Connection.ReadTransaction -> [ItemType] {
let byKey = inTransactionByKey
return { transaction in
let keys = keys ?? transaction.keysInCollection(ItemType.collection)
return keys.flatMap(byKey(transaction))
}
}
/**
Reads the item at a given index.
- parameter index: a YapDB.Index
- returns: an optional `ItemType`
*/
public func atIndex(index: YapDB.Index) -> ItemType? {
return sync(atIndexInTransaction(index))
}
/**
Reads the items at the indexes.
- parameter indexes: a SequenceType of YapDB.Index values
- returns: an array of `ItemType`
*/
public func atIndexes<
Indexes where
Indexes: SequenceType,
Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) -> [ItemType] {
return sync(atIndexesInTransaction(indexes))
}
/**
Reads the item at the key.
- parameter key: a String
- returns: an optional `ItemType`
*/
public func byKey(key: String) -> ItemType? {
return sync(byKeyInTransaction(key))
}
/**
Reads the items by the keys.
- parameter keys: a SequenceType of String values
- returns: an array of `ItemType`
*/
public func byKeys<
Keys where
Keys: SequenceType,
Keys.Generator.Element == String>(keys: Keys) -> [ItemType] {
return sync(byKeysInTransaction(Array(keys)))
}
/**
Reads all the `ItemType` in the database.
- returns: an array of `ItemType`
*/
public func all() -> [ItemType] {
return sync(byKeysInTransaction())
}
/**
Returns th existing items and missing keys..
- parameter keys: a SequenceType of String values
- returns: a tuple of type `([ItemType], [String])`
*/
public func filterExisting(keys: [String]) -> (existing: [ItemType], missing: [String]) {
let existingInTransaction = byKeysInTransaction(keys)
return sync { transaction -> ([ItemType], [String]) in
let existing = existingInTransaction(transaction)
let existingKeys = existing.map(keyForPersistable)
let missingKeys = keys.filter { !existingKeys.contains($0) }
return (existing, missingKeys)
}
}
}
|
c1b9306002fd9dcf5258d069ad6bd251
| 30.88 | 185 | 0.674055 | false | false | false | false |
material-motion/material-motion-swift
|
refs/heads/develop
|
tests/unit/operator/foundation/_mapTests.swift
|
apache-2.0
|
1
|
/*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
import IndefiniteObservable
import MaterialMotion
class _mapTests: XCTestCase {
func testSubscription() {
let value = 10
let scalar = 10
let observable = MotionObservable<Int> { observer in
observer.next(value)
return noopDisconnect
}
let valueReceived = expectation(description: "Value was received")
let _ = observable._map { value in
return value * scalar
}.subscribeToValue {
if $0 == value * scalar {
valueReceived.fulfill()
}
}
waitForExpectations(timeout: 0)
}
func testBasicAnimationMapping() {
let fromValue = 10
let toValue = -2
let byValue = -5
let scalar = 10
let observable = MotionObservable<Int> { observer in
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = fromValue
animation.toValue = toValue
animation.byValue = byValue
let add = CoreAnimationChannelAdd(animation: animation, key: "a", onCompletion: { })
observer.coreAnimation?(CoreAnimationChannelEvent.add(add))
return noopDisconnect
}
let eventReceived = expectation(description: "Event was received")
let _ = observable._map { value in
return value * scalar
}.subscribe(next: { _ in }, coreAnimation: { event in
switch event {
case .add(let add):
let animation = add.animation as! CABasicAnimation
XCTAssertEqual(animation.fromValue as! Int, fromValue * scalar)
XCTAssertEqual(animation.toValue as! Int, toValue * scalar)
XCTAssertEqual(animation.byValue as! Int, byValue * scalar)
eventReceived.fulfill()
default: ()
}
}, visualization: { _ in })
waitForExpectations(timeout: 0)
}
func testKeyframeAnimationMapping() {
let values = [10, 20, 50]
let scalar = 10
let observable = MotionObservable<Int> { observer in
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.values = values
let add = CoreAnimationChannelAdd(animation: animation, key: "a", onCompletion: { })
observer.coreAnimation?(CoreAnimationChannelEvent.add(add))
return noopDisconnect
}
let eventReceived = expectation(description: "Event was received")
let _ = observable._map { value in
return value * scalar
}.subscribe(next: { _ in }, coreAnimation: { event in
switch event {
case .add(let add):
let animation = add.animation as! CAKeyframeAnimation
XCTAssertEqual(values.map { $0 * scalar }, animation.values as! [Int])
eventReceived.fulfill()
default: ()
}
}, visualization: { _ in })
waitForExpectations(timeout: 0)
}
func testInitialVelocityMapping() {
let velocity = 10
let scalar = 10
let observable = MotionObservable<Int> { observer in
let animation = CABasicAnimation(keyPath: "opacity")
var add = CoreAnimationChannelAdd(animation: animation, key: "a", onCompletion: { })
add.initialVelocity = velocity
observer.coreAnimation?(CoreAnimationChannelEvent.add(add))
return noopDisconnect
}
let eventReceived = expectation(description: "Event was received")
let _ = observable._map(transformVelocity: true) { value in
return value * scalar
}.subscribe(next: { _ in }, coreAnimation: { event in
switch event {
case .add(let add):
XCTAssertEqual(add.initialVelocity as! Int, velocity * scalar)
eventReceived.fulfill()
default: ()
}
}, visualization: { _ in })
waitForExpectations(timeout: 0)
}
func testAnimationIsCopied() {
var originalAnimation: CABasicAnimation?
let observable = MotionObservable<Int> { observer in
originalAnimation = CABasicAnimation()
let add = CoreAnimationChannelAdd(animation: originalAnimation!, key: "a", onCompletion: { })
observer.coreAnimation?(CoreAnimationChannelEvent.add(add))
return noopDisconnect
}
let eventReceived = expectation(description: "Event was received")
let _ = observable._map { value in
return value * 10
}.subscribe(next: { _ in }, coreAnimation: { event in
switch event {
case .add(let add):
let animation = add.animation as! CABasicAnimation
XCTAssertNotEqual(originalAnimation, animation)
eventReceived.fulfill()
default: ()
}
}, visualization: { _ in })
waitForExpectations(timeout: 0)
}
}
|
0fbb85aa962834f3946991b2f9bc49f0
| 29.921687 | 99 | 0.666667 | false | false | false | false |
daniel-barros/TV-Calendar
|
refs/heads/master
|
TraktKit/Common/TraktSearchResult.swift
|
gpl-3.0
|
1
|
//
// TraktSearchResult.swift
// TraktKit
//
// Created by Maximilian Litteral on 4/13/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
public struct TraktSearchResult: TraktProtocol {
public let type: String // Can be movie, show, episode, person, list
public let score: Double?
public let movie: TraktMovie?
public let show: TraktShow?
public let episode: TraktEpisode?
public let person: Person?
public let list: TraktList?
// Initialize
public init(type: String, score: Double, movie: TraktMovie?, show: TraktShow?, episode: TraktEpisode?, person: Person?, list: TraktList?) {
self.type = type
self.score = score
self.movie = movie
self.show = show
self.episode = episode
self.person = person
self.list = list
}
public init?(json: RawJSON?) {
guard
let json = json,
let type = json["type"] as? String else { return nil }
self.type = type
self.score = json["score"] as? Double
self.movie = TraktMovie(json: json["movie"] as? RawJSON)
self.show = TraktShow(json: json["show"] as? RawJSON)
self.episode = TraktEpisode(json: json["episode"] as? RawJSON)
self.person = Person(json: json["person"] as? RawJSON)
self.list = TraktList(json: json["list"] as? RawJSON)
}
}
|
ab7f9788758550c853cbd4d617258f7c
| 32.266667 | 143 | 0.589178 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
refs/heads/master
|
DYLive/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift
|
mit
|
3
|
//
// CPListItem+Kingfisher.swift
// Kingfisher
//
// Created by Wayne Hartman on 2021-08-29.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(CarPlay) && !targetEnvironment(macCatalyst)
import CarPlay
@available(iOS 14.0, *)
extension KingfisherWrapper where Base: CPListItem {
// MARK: Setting Image
/// Sets an image to the image view with a source.
///
/// - Parameters:
/// - source: The `Source` object contains information about the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
///
/// Internally, this method will use `KingfisherManager` to get the requested source
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? []))
return setImage(
with: source,
placeholder: placeholder,
parsedOptions: options,
progressBlock: progressBlock,
completionHandler: completionHandler
)
}
/// Sets an image to the image view with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
///
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
parsedOptions: KingfisherParsedOptionsInfo,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
/**
* In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
* to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
* which allows >=14.5 SDK to set a `nil` image. This compile check allows
* newer SDK users to set the image to `nil`, while still allowing older SDK
* users to compile the framework.
*/
#if compiler(>=5.4)
self.base.setImage(placeholder)
#else
if let placeholder = placeholder {
self.base.setImage(placeholder)
}
#endif
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = parsedOptions
if !options.keepCurrentImageWhileLoading {
/**
* In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
* to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
* which allows >=14.5 SDK to set a `nil` image. This compile check allows
* newer SDK users to set the image to `nil`, while still allowing older SDK
* users to compile the framework.
*/
#if compiler(>=5.4)
self.base.setImage(placeholder)
#else // Let older SDK users deal with the older behavior.
if let placeholder = placeholder {
self.base.setImage(placeholder)
}
#endif
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.setImage(image)
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
self.base.setImage(value.image)
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
/**
* In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
* to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
* which allows >=14.5 SDK to set a `nil` image. This compile check allows
* newer SDK users to set the image to `nil`, while still allowing older SDK
* users to compile the framework.
*/
#if compiler(>=5.4)
self.base.setImage(image)
#else // Let older SDK users deal with the older behavior.
if let unwrapped = image {
self.base.setImage(unwrapped)
}
#endif
} else {
#if compiler(>=5.4)
self.base.setImage(nil)
#endif
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
// MARK: Cancelling Image
/// Cancel the image download task bounded to the image view if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
private var taskIdentifierKey: Void?
private var imageTaskKey: Void?
// MARK: Properties
extension KingfisherWrapper where Base: CPListItem {
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
}
#endif
|
b343cc8870bf19ade5861cc88ab64501
| 43.124031 | 119 | 0.580991 | false | false | false | false |
matsprea/omim
|
refs/heads/master
|
iphone/Maps/Core/Theme/Renderers/UITextFieldRenderer.swift
|
apache-2.0
|
1
|
extension UITextField {
@objc override func applyTheme() {
for style in StyleManager.shared.getStyle(styleName)
where !style.isEmpty && !style.hasExclusion(view: self) {
UITextFieldRenderer.render(self, style: style)
}
}
@objc override func sw_didMoveToWindow() {
guard UIApplication.shared.keyWindow === window else {
sw_didMoveToWindow();
return
}
applyTheme()
isStyleApplied = true
sw_didMoveToWindow();
}
}
class UITextFieldRenderer {
class func render(_ control: UITextField, style: Style) {
var placeholderAttributes = [NSAttributedString.Key : Any]()
if let backgroundColor = style.backgroundColor {
control.backgroundColor = backgroundColor
}
if let font = style.font {
control.font = font
placeholderAttributes[NSAttributedString.Key.font] = font
}
if let fontColor = style.fontColor {
control.textColor = fontColor
}
if let tintColor = style.tintColor {
control.tintColor = tintColor
placeholderAttributes[NSAttributedString.Key.foregroundColor] = tintColor
}
if let attributedPlaceholder = control.attributedPlaceholder, !attributedPlaceholder.string.isEmpty {
control.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string,
attributes: placeholderAttributes)
}
}
}
|
36397311d621b6624c29320f1a9a1f2c
| 31.837209 | 105 | 0.680595 | false | false | false | false |
mohitathwani/swift-corelibs-foundation
|
refs/heads/master
|
Foundation/NSNumber.swift
|
apache-2.0
|
1
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFNumberSInt8Type = CFNumberType.sInt8Type
internal let kCFNumberSInt16Type = CFNumberType.sInt16Type
internal let kCFNumberSInt32Type = CFNumberType.sInt32Type
internal let kCFNumberSInt64Type = CFNumberType.sInt64Type
internal let kCFNumberFloat32Type = CFNumberType.float32Type
internal let kCFNumberFloat64Type = CFNumberType.float64Type
internal let kCFNumberCharType = CFNumberType.charType
internal let kCFNumberShortType = CFNumberType.shortType
internal let kCFNumberIntType = CFNumberType.intType
internal let kCFNumberLongType = CFNumberType.longType
internal let kCFNumberLongLongType = CFNumberType.longLongType
internal let kCFNumberFloatType = CFNumberType.floatType
internal let kCFNumberDoubleType = CFNumberType.doubleType
internal let kCFNumberCFIndexType = CFNumberType.cfIndexType
internal let kCFNumberNSIntegerType = CFNumberType.nsIntegerType
internal let kCFNumberCGFloatType = CFNumberType.cgFloatType
internal let kCFNumberSInt128Type = CFNumberType(rawValue: 17)!
#else
internal let kCFNumberSInt128Type: CFNumberType = 17
#endif
extension Int : _ObjectTypeBridgeable {
public init(_ number: NSNumber) {
self = number.intValue
}
public typealias _ObjectType = NSNumber
public func _bridgeToObjectiveC() -> _ObjectType {
return NSNumber(value: self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Int?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Int?) -> Bool {
result = source.intValue
return true
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Int {
if let object = source {
var value: Int?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return 0
}
}
}
extension UInt : _ObjectTypeBridgeable {
public init(_ number: NSNumber) {
self = number.uintValue
}
public typealias _ObjectType = NSNumber
public func _bridgeToObjectiveC() -> _ObjectType {
return NSNumber(value: self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout UInt?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout UInt?) -> Bool {
result = source.uintValue
return true
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> UInt {
if let object = source {
var value: UInt?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return 0
}
}
}
extension Float : _ObjectTypeBridgeable {
public init(_ number: NSNumber) {
self = number.floatValue
}
public typealias _ObjectType = NSNumber
public func _bridgeToObjectiveC() -> _ObjectType {
return NSNumber(value: self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Float?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Float?) -> Bool {
result = source.floatValue
return true
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Float {
if let object = source {
var value: Float?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return 0.0
}
}
}
extension Double : _ObjectTypeBridgeable {
public init(_ number: NSNumber) {
self = number.doubleValue
}
public typealias _ObjectType = NSNumber
public func _bridgeToObjectiveC() -> _ObjectType {
return NSNumber(value: self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Double?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Double?) -> Bool {
result = source.doubleValue
return true
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Double {
if let object = source {
var value: Double?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return 0.0
}
}
}
extension Bool : _ObjectTypeBridgeable {
public init(_ number: NSNumber) {
self = number.boolValue
}
public typealias _ObjectType = NSNumber
public func _bridgeToObjectiveC() -> _ObjectType {
return unsafeBitCast(self ? kCFBooleanTrue : kCFBooleanFalse, to: NSNumber.self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout Bool?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout Bool?) -> Bool {
result = source.boolValue
return true
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> Bool {
if let object = source {
var value: Bool?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return false
}
}
}
extension Bool : _CFBridgeable {
typealias CFType = CFBoolean
var _cfObject: CFType {
return self ? kCFBooleanTrue : kCFBooleanFalse
}
}
extension NSNumber : ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, ExpressibleByBooleanLiteral {
}
open class NSNumber : NSValue {
typealias CFType = CFNumber
// This layout MUST be the same as CFNumber so that they are bridgeable
private var _base = _CFInfo(typeID: CFNumberGetTypeID())
private var _pad: UInt64 = 0
internal let _objCType: _NSSimpleObjCType
internal var _cfObject: CFType {
return unsafeBitCast(self, to: CFType.self)
}
open override var hash: Int {
return Int(bitPattern: CFHash(_cfObject))
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Int:
return intValue == other
case let other as Double:
return doubleValue == other
case let other as Bool:
return boolValue == other
case let other as NSNumber:
return CFEqual(_cfObject, other._cfObject)
default:
return false
}
}
open override var objCType: UnsafePointer<Int8> {
return UnsafePointer<Int8>(bitPattern: UInt(_objCType.rawValue.value))!
}
deinit {
_CFDeinit(self)
}
public init(value: Int8) {
_objCType = .Char
super.init()
_CFNumberInitInt8(_cfObject, value)
}
public init(value: UInt8) {
_objCType = .UChar
super.init()
_CFNumberInitUInt8(_cfObject, value)
}
public init(value: Int16) {
_objCType = .Short
super.init()
_CFNumberInitInt16(_cfObject, value)
}
public init(value: UInt16) {
_objCType = .UShort
super.init()
_CFNumberInitUInt16(_cfObject, value)
}
public init(value: Int32) {
_objCType = .Long
super.init()
_CFNumberInitInt32(_cfObject, value)
}
public init(value: UInt32) {
_objCType = .ULong
super.init()
_CFNumberInitUInt32(_cfObject, value)
}
public init(value: Int) {
_objCType = .Int
super.init()
_CFNumberInitInt(_cfObject, value)
}
public init(value: UInt) {
_objCType = .UInt
super.init()
_CFNumberInitUInt(_cfObject, value)
}
public init(value: Int64) {
_objCType = .LongLong
super.init()
_CFNumberInitInt64(_cfObject, value)
}
public init(value: UInt64) {
_objCType = .ULongLong
super.init()
_CFNumberInitUInt64(_cfObject, value)
}
public init(value: Float) {
_objCType = .Float
super.init()
_CFNumberInitFloat(_cfObject, value)
}
public init(value: Double) {
_objCType = .Double
super.init()
_CFNumberInitDouble(_cfObject, value)
}
public init(value: Bool) {
_objCType = .Bool
super.init()
_CFNumberInitBool(_cfObject, value)
}
override internal init() {
_objCType = .Undef
super.init()
}
public required convenience init(bytes buffer: UnsafeRawPointer, objCType: UnsafePointer<Int8>) {
guard let type = _NSSimpleObjCType(UInt8(objCType.pointee)) else {
fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'")
}
switch type {
case .Bool:
self.init(value:buffer.load(as: Bool.self))
case .Char:
self.init(value:buffer.load(as: Int8.self))
case .UChar:
self.init(value:buffer.load(as: UInt8.self))
case .Short:
self.init(value:buffer.load(as: Int16.self))
case .UShort:
self.init(value:buffer.load(as: UInt16.self))
case .Int, .Long:
self.init(value:buffer.load(as: Int32.self))
case .UInt, .ULong:
self.init(value:buffer.load(as: UInt32.self))
case .LongLong:
self.init(value:buffer.load(as: Int64.self))
case .ULongLong:
self.init(value:buffer.load(as: UInt64.self))
case .Float:
self.init(value:buffer.load(as: Float.self))
case .Double:
self.init(value:buffer.load(as: Double.self))
default:
fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'")
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.number") {
let number = aDecoder._decodePropertyListForKey("NS.number")
if let val = number as? Double {
self.init(value:val)
} else if let val = number as? Int {
self.init(value:val)
} else if let val = number as? Bool {
self.init(value:val)
} else {
return nil
}
} else {
if aDecoder.containsValue(forKey: "NS.boolval") {
self.init(value: aDecoder.decodeBool(forKey: "NS.boolval"))
} else if aDecoder.containsValue(forKey: "NS.intval") {
self.init(value: aDecoder.decodeInt64(forKey: "NS.intval"))
} else if aDecoder.containsValue(forKey: "NS.dblval") {
self.init(value: aDecoder.decodeDouble(forKey: "NS.dblval"))
} else {
return nil
}
}
}
open var int8Value: Int8 {
var val: Int8 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int8>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberCharType, value)
}
return val
}
open var uint8Value: UInt8 {
var val: UInt8 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt8>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberCharType, value)
}
return val
}
open var int16Value: Int16 {
var val: Int16 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int16>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberShortType, value)
}
return val
}
open var uint16Value: UInt16 {
var val: UInt16 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt16>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberShortType, value)
}
return val
}
open var int32Value: Int32 {
var val: Int32 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int32>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberIntType, value)
}
return val
}
open var uint32Value: UInt32 {
var val: UInt32 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt32>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberIntType, value)
}
return val
}
open var int64Value: Int64 {
var val: Int64 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int64>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberLongLongType, value)
}
return val
}
open var uint64Value: UInt64 {
var val: UInt64 = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt64>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberLongLongType, value)
}
return val
}
open var floatValue: Float {
var val: Float = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Float>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberFloatType, value)
}
return val
}
open var doubleValue: Double {
var val: Double = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Double>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberDoubleType, value)
}
return val
}
open var boolValue: Bool {
return int64Value != 0
}
open var intValue: Int {
var val: Int = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<Int>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberLongType, value)
}
return val
}
open var uintValue: UInt {
var val: UInt = 0
withUnsafeMutablePointer(to: &val) { (value: UnsafeMutablePointer<UInt>) -> Void in
CFNumberGetValue(_cfObject, kCFNumberLongType, value)
}
return val
}
open var stringValue: String {
return description(withLocale: nil)
}
/// Create an instance initialized to `value`.
public required convenience init(integerLiteral value: Int) {
self.init(value: value)
}
/// Create an instance initialized to `value`.
public required convenience init(floatLiteral value: Double) {
self.init(value: value)
}
/// Create an instance initialized to `value`.
public required convenience init(booleanLiteral value: Bool) {
self.init(value: value)
}
open func compare(_ otherNumber: NSNumber) -> ComparisonResult {
return ._fromCF(CFNumberCompare(_cfObject, otherNumber._cfObject, nil))
}
open func description(withLocale locale: Locale?) -> String {
let aLocale = locale
let formatter: CFNumberFormatter
if (aLocale == nil) {
formatter = CFNumberFormatterCreate(nil, CFLocaleCopyCurrent(), kCFNumberFormatterNoStyle)
CFNumberFormatterSetProperty(formatter, kCFNumberFormatterMaxFractionDigits, 15._bridgeToObjectiveC())
} else {
formatter = CFNumberFormatterCreate(nil, aLocale?._cfObject, kCFNumberFormatterDecimalStyle)
}
return CFNumberFormatterCreateStringWithNumber(nil, formatter, self._cfObject)._swiftObject
}
override open var _cfTypeID: CFTypeID {
return CFNumberGetTypeID()
}
open override var description: String {
return description(withLocale: nil)
}
internal func _cfNumberType() -> CFNumberType {
switch objCType.pointee {
case 0x42: return kCFNumberCharType
case 0x63: return kCFNumberCharType
case 0x43: return kCFNumberShortType
case 0x73: return kCFNumberShortType
case 0x53: return kCFNumberIntType
case 0x69: return kCFNumberIntType
case 0x49: return Int(uint32Value) < Int(Int32.max) ? kCFNumberIntType : kCFNumberLongLongType
case 0x6C: return kCFNumberLongType
case 0x4C: return uintValue < UInt(Int.max) ? kCFNumberLongType : kCFNumberLongLongType
case 0x66: return kCFNumberFloatType
case 0x64: return kCFNumberDoubleType
case 0x71: return kCFNumberLongLongType
case 0x51: return kCFNumberLongLongType
default: fatalError()
}
}
internal func _getValue(_ valuePtr: UnsafeMutableRawPointer, forType type: CFNumberType) -> Bool {
switch type {
case kCFNumberSInt8Type:
valuePtr.assumingMemoryBound(to: Int8.self).pointee = int8Value
break
case kCFNumberSInt16Type:
valuePtr.assumingMemoryBound(to: Int16.self).pointee = int16Value
break
case kCFNumberSInt32Type:
valuePtr.assumingMemoryBound(to: Int32.self).pointee = int32Value
break
case kCFNumberSInt64Type:
valuePtr.assumingMemoryBound(to: Int64.self).pointee = int64Value
break
case kCFNumberSInt128Type:
struct CFSInt128Struct {
var high: Int64
var low: UInt64
}
let val = int64Value
valuePtr.assumingMemoryBound(to: CFSInt128Struct.self).pointee = CFSInt128Struct.init(high: (val < 0) ? -1 : 0, low: UInt64(bitPattern: val))
break
case kCFNumberFloat32Type:
valuePtr.assumingMemoryBound(to: Float.self).pointee = floatValue
break
case kCFNumberFloat64Type:
valuePtr.assumingMemoryBound(to: Double.self).pointee = doubleValue
default: fatalError()
}
return true
}
open override func encode(with aCoder: NSCoder) {
if !aCoder.allowsKeyedCoding {
NSUnimplemented()
} else {
if let keyedCoder = aCoder as? NSKeyedArchiver {
keyedCoder._encodePropertyList(self)
} else {
if CFGetTypeID(self) == CFBooleanGetTypeID() {
aCoder.encode(boolValue, forKey: "NS.boolval")
} else {
switch objCType.pointee {
case 0x42:
aCoder.encode(boolValue, forKey: "NS.boolval")
break
case 0x63: fallthrough
case 0x43: fallthrough
case 0x73: fallthrough
case 0x53: fallthrough
case 0x69: fallthrough
case 0x49: fallthrough
case 0x6C: fallthrough
case 0x4C: fallthrough
case 0x71: fallthrough
case 0x51:
aCoder.encode(int64Value, forKey: "NS.intval")
case 0x66: fallthrough
case 0x64:
aCoder.encode(doubleValue, forKey: "NS.dblval")
default: break
}
}
}
}
}
open override var classForCoder: AnyClass { return NSNumber.self }
}
extension CFNumber : _NSBridgeable {
typealias NSType = NSNumber
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) }
}
internal func _CFSwiftNumberGetType(_ obj: CFTypeRef) -> CFNumberType {
return unsafeBitCast(obj, to: NSNumber.self)._cfNumberType()
}
internal func _CFSwiftNumberGetValue(_ obj: CFTypeRef, _ valuePtr: UnsafeMutableRawPointer, _ type: CFNumberType) -> Bool {
return unsafeBitCast(obj, to: NSNumber.self)._getValue(valuePtr, forType: type)
}
internal func _CFSwiftNumberGetBoolValue(_ obj: CFTypeRef) -> Bool {
return unsafeBitCast(obj, to: NSNumber.self).boolValue
}
|
b63600941e54e21d663348b2f9ab46d2
| 32.25832 | 153 | 0.617698 | false | false | false | false |
arturjaworski/Colorizer
|
refs/heads/master
|
Sources/colorizer/Commands/GenerateCommand.swift
|
mit
|
1
|
import Foundation
import SwiftCLI
import PathKit
import AppKit.NSColor
class GenerateCommand: Command {
let name = "generate"
let shortDescription = "Generating CLR pallete (.clr file) from .txt file."
let signature = "<InputFile> <OutputFile>"
enum CommandError: Error {
case noInputFile
case invalidInputFile
var description: String {
switch self {
case .noInputFile: return "InputFile do not exists. Please provide .txt file."
case .invalidInputFile: return "InputFile is invalid. Please provide valid .txt file."
}
}
}
func execute(arguments: CommandArguments) throws {
do {
let inputFilePath = Path(arguments.requiredArgument("InputFile"))
if !inputFilePath.isFile {
throw CommandError.noInputFile
}
var colorFileParser: ColorFileParser? = nil
do {
switch inputFilePath.`extension` ?? "" {
case "txt":
colorFileParser = try TextColorFileParser(path: inputFilePath)
default: ()
}
}
catch {
throw CommandError.invalidInputFile
}
guard let parser = colorFileParser else {
throw CommandError.invalidInputFile
}
let outputFileString = arguments.requiredArgument("OutputFile")
let colorList = NSColorList(name: outputFileString)
for (name, color) in parser.colors {
colorList.setColor(color, forKey: name)
}
colorList.write(toFile: outputFileString)
print("Generated successfully.")
}
catch let error as CommandError {
print("Error: \(error.description)")
}
}
}
|
4fafec11ff32e90c2b17ffa6aa2490fd
| 30 | 98 | 0.562434 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKitMock/MockBiometryProvider.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformUIKit
import RxSwift
final class MockBiometryProvider: BiometryProviding {
var supportedBiometricsType: Biometry.BiometryType = .touchID
let canAuthenticate: Result<Biometry.BiometryType, Biometry.EvaluationError>
var configuredType: Biometry.BiometryType
let configurationStatus: Biometry.Status
private let authenticatesSuccessfully: Bool
init(
authenticatesSuccessfully: Bool,
canAuthenticate: Result<Biometry.BiometryType, Biometry.EvaluationError>,
configuredType: Biometry.BiometryType,
configurationStatus: Biometry.Status
) {
self.authenticatesSuccessfully = authenticatesSuccessfully
self.canAuthenticate = canAuthenticate
self.configuredType = configuredType
self.configurationStatus = configurationStatus
}
func authenticate(reason: Biometry.Reason) -> Single<Void> {
switch canAuthenticate {
case .success:
return .just(())
case .failure(let error):
return .error(error)
}
}
}
|
067e47422d7e8fad954ef63a55d23d64
| 32.294118 | 81 | 0.713781 | false | true | false | false |
mantyr/libui
|
refs/heads/master
|
osxaltest/button.swift
|
mit
|
1
|
// 31 july 2015
import Cocoa
class Button : NSButton, Control {
private var parent: Control?
init(_ text: String) {
self.parent = nil
super.init(frame: NSZeroRect)
self.title = text
self.setButtonType(NSButtonType.MomentaryPushInButton)
self.bordered = true
self.bezelStyle = NSBezelStyle.RoundedBezelStyle
self.font = NSFont.systemFontOfSize(NSFont.systemFontSizeForControlSize(NSControlSize.RegularControlSize))
self.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
fatalError("can't use this constructor, sorry")
}
func View() -> NSView {
return self
}
func SetParent(p: Control) {
self.parent = p
}
}
|
2c75ae6ba15872c31aad1d817e48ff96
| 21.6 | 108 | 0.744838 | false | false | false | false |
PwCSDC/PwCiOSKit
|
refs/heads/master
|
PwCiOSKit/PwCUtilities.swift
|
mit
|
1
|
//
// PwCUtilities.swift
// PwCMobileKit
//
// Created by ahu039 on 7/20/17.
// Copyright © 2017 PwC Inc. All rights reserved.
//
import UIKit
open class PwCUtilities: NSObject {
/*
* Get value from NSUserDefault
*/
open class func userDefaultValue(forKey key: String) -> AnyObject? {
return UserDefaults.standard.object(forKey: key) as AnyObject?
}
/*
* Set and sync value into NSUserDefault
*/
open class func setUserDefault(_ object: Any, forKey key: String) {
UserDefaults.standard.set(object, forKey: key)
UserDefaults.standard.synchronize()
}
/*
* Remove key/value from UserDefault, and synchronize
*/
open class func removeUserDefault(forKey key: String) {
let value = self.userDefaultValue(forKey: key) as? String
if value != nil {
UserDefaults.standard.removeObject(forKey: key)
UserDefaults.standard.synchronize()
}
}
/*
* Allow alphabet, numeric characters, '-', '_' and '.'
*/
open class func removeSpecialCharInURL(_ inputString: String) -> String {
let strWithoutSpace = inputString.replacingOccurrences(of: " ", with:"-")
let okayChars : Set<Character> =
Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_.".characters)
let replacedString = String(strWithoutSpace.characters.filter {okayChars.contains($0) })
return replacedString
}
/**
* Load UIViewController from Main Storyboard with name:Main.storyboard
*/
open class func loadViewControllerFromMainStoryboard (_ nibName: String) -> UIViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: nibName)
return viewController
}
/**
* Return true if is landscape, otherwise false
*/
open class func isLandscape() -> Bool {
if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
return true
}
return false
}
/**
* Return true if is a valid email address, othereise false
*/
open class func isValidEmail(_ emailString: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: emailString)
}
/**
* Return true if is integer value eg. 10
*/
open class func isInteger(_ textString: String) -> Bool {
let intRegEx = "^[0-9]*$"
let intTest = NSPredicate(format:"SELF MATCHES %@", intRegEx)
return intTest.evaluate(with: textString)
}
/**
* Return true if match eg. 91.12
*/
open class func isDigital(_ textString: String) -> Bool {
let intRegEx = "^[0-9]+(.[0-9]{1,2})?$"
let intTest = NSPredicate(format:"SELF MATCHES %@", intRegEx)
return intTest.evaluate(with: textString)
}
/**
* Should match format ***-***-****
*/
open class func isValidUSPhone(_ phoneString: String) -> Bool {
let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
return phoneTest.evaluate(with: phoneString)
}
/**
* Started with 'http' or 'https' and check standard url format
*/
open class func isValidHttpURL(_ candidate : String) -> Bool {
let urlRegEx = "(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
let urlTest = NSPredicate(format:"SELF MATCHES %@", urlRegEx)
return urlTest.evaluate(with: candidate)
}
/**
* Get App Version # from info.plist
*/
open class func appVersion() -> String {
let infoDictionary = Bundle.main.infoDictionary
let majorVersion : AnyObject? = infoDictionary! ["CFBundleShortVersionString"] as AnyObject?
return majorVersion as! String
}
/**
* Parsing base64 String into Image, possibly return nil if the input parameter is not base64 String of a valid image
* - parameter strEncodeData: base64 String
* - returns: The image parsed by base64 string, or nil if not valid base64 string passed over
*/
open class func base64StringToImage(_ strEncodeData: String) -> UIImage? {
let baseData = Data(base64Encoded: strEncodeData, options: .ignoreUnknownCharacters)
let image = UIImage(data: baseData!)
return image
}
/**
* Document to base 64 string
*/
open class func documentToBase64String(DocumentPath documentPath: String) -> String? {
let documentData = try? Data(contentsOf: URL(fileURLWithPath: documentPath))
if documentData != nil {
let documentBase = documentData!.base64EncodedString(options: .lineLength64Characters)
return documentBase
}
return nil
}
}
|
4f74fa8721f92cad83f6daa0af614075
| 33.455782 | 121 | 0.615795 | false | true | false | false |
tomasen/NEAppHTTPProxyProvider
|
refs/heads/master
|
AppHTTPProxyProvider.swift
|
mit
|
1
|
//
// AppHTTPProxyProvider.swift
//
// Created by Tomasen on 2/5/16.
// Copyright © 2016 PINIDEA LLC. All rights reserved.
//
import NetworkExtension
import CocoaAsyncSocket
struct HTTPProxySet {
var host: String
var port: UInt16
}
var proxy = HTTPProxySet(host: "127.0.0.1", port: 3028)
/// A AppHTTPProxyProvider sub-class that implements the client side of the http proxy tunneling protocol.
class AppHTTPProxyProvider: NEAppProxyProvider {
/// Begin the process of establishing the tunnel.
override func startProxyWithOptions(options: [String : AnyObject]?, completionHandler: (NSError?) -> Void) {
completionHandler(nil)
}
/// Begin the process of stopping the tunnel.
override func stopProxyWithReason(reason: NEProviderStopReason, completionHandler: () -> Void) {
completionHandler()
}
/// Handle a new flow of network data created by an application.
override func handleNewFlow(flow: (NEAppProxyFlow?)) -> Bool {
if let TCPFlow = flow as? NEAppProxyTCPFlow {
let conn = ClientAppHTTPProxyConnection(flow: TCPFlow)
conn.open()
}
return false
}
}
/// An object representing the client side of a logical flow of network data in the SimpleTunnel tunneling protocol.
class ClientAppHTTPProxyConnection : NSObject, GCDAsyncSocketDelegate {
// MARK: Constants
let bufferSize: UInt = 4096
let timeout = 30.0
let pattern = "\n\n".dataUsingEncoding(NSUTF8StringEncoding)
// MARK: Properties
/// The NEAppProxyFlow object corresponding to this connection.
let TCPFlow: NEAppProxyTCPFlow
// MARK: Initializers
var sock: GCDAsyncSocket!
init(flow: NEAppProxyTCPFlow) {
TCPFlow = flow
}
func open() {
sock = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
do {
try sock.connectToHost(proxy.host, onPort: proxy.port, withTimeout: 30.0)
} catch {
TCPFlow.closeReadWithError(NSError(domain: NEAppProxyErrorDomain, code: NEAppProxyFlowError.NotConnected.rawValue, userInfo: nil))
return
}
}
func socket(sock: GCDAsyncSocket, didConnectToHost host:String, port p:UInt16) {
print("Connected to \(host) on port \(p).")
let remoteHost = (TCPFlow.remoteEndpoint as! NWHostEndpoint).hostname
let remotePort = (TCPFlow.remoteEndpoint as! NWHostEndpoint).port
// 1. send CONNECT
// CONNECT www.google.com:80 HTTP/1.1
sock.writeData(
"CONNECT \(remoteHost):\(remotePort) HTTP/1.1\n\n"
.dataUsingEncoding(NSUTF8StringEncoding),
withTimeout: timeout,
tag: 1)
}
func didReadFlow(data: NSData?, error: NSError?) {
// 7. did read from flow
// 8. write flow data to proxy
sock.writeData(data, withTimeout: timeout, tag: 0)
// 9. keep reading from flow
TCPFlow.readDataWithCompletionHandler(self.didReadFlow)
}
func socket(sock: GCDAsyncSocket!, didWriteDataWithTag tag: Int) {
if tag == 1 {
// 2. CONNECT header sent
// 3. begin to read from proxy server
sock.readDataToLength(bufferSize, withTimeout: timeout, tag: 1)
}
}
func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
if tag == 1 {
// 4. read 1st proxy server response of CONNECT
let range = data.rangeOfData(pattern!,
options: NSDataSearchOptions(rawValue: 0),
range: NSMakeRange(0, data.length))
if range.location != NSNotFound {
let ret = data.rangeOfData("200".dataUsingEncoding(NSUTF8StringEncoding)!,
options: NSDataSearchOptions(rawValue: 0),
range: NSMakeRange(0, range.location))
if ret.location != NSNotFound {
let loc = range.location+range.length
if data.length > loc {
// 5. write to flow if there is data already
TCPFlow.writeData(data.subdataWithRange(NSMakeRange(loc, data.length - loc)), withCompletionHandler: { error in })
}
// 6. begin to read from Flow
TCPFlow.readDataWithCompletionHandler(self.didReadFlow)
// 6.5 keep reading from proxy server
sock.readDataToLength(bufferSize, withTimeout: timeout, tag: 0)
return
}
}
// Error: CONNECT failed
TCPFlow.closeReadWithError(NSError(domain: NEAppProxyErrorDomain, code: NEAppProxyFlowError.NotConnected.rawValue, userInfo: nil))
sock.disconnect()
return
}
// 10. writing any data followed to flow
TCPFlow.writeData(data, withCompletionHandler: { error in })
// 11. keep reading from proxy server
sock.readDataToLength(bufferSize, withTimeout: timeout, tag: 0)
}
}
|
0e8cc611863f8244b99aa733dab9b328
| 34.245033 | 142 | 0.597068 | false | false | false | false |
jairoeli/Instasheep
|
refs/heads/master
|
InstagramFirebase/InstagramFirebase/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// InstagramFirebase
//
// Created by Jairo Eli de Leon on 3/21/17.
// Copyright © 2017 DevMountain. All rights reserved.
//
import UIKit
import Firebase
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
window = UIWindow()
window?.rootViewController = MainTabBarController()
attemtpRegisterForNotifications(application: application)
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Registered for notifications:", deviceToken)
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Registered with FCM with token:", fcmToken)
}
// list for user notificaitons
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let followerId = userInfo["followerId"] as? String {
print(followerId)
// push the UserProfileController for followerId
let userProfileController = UserProfileController(collectionViewLayout: UICollectionViewFlowLayout())
userProfileController.userID = followerId
// access the main UI from AppDelegate
if let mainTabBarController = window?.rootViewController as? MainTabBarController {
mainTabBarController.selectedIndex = 0
mainTabBarController.presentedViewController?.dismiss(animated: true, completion: nil)
if let homeNavigationController = mainTabBarController.viewControllers?.first as? UINavigationController {
homeNavigationController.pushViewController(userProfileController, animated: true)
}
}
}
}
private func attemtpRegisterForNotifications(application: UIApplication) {
print("Ateempting to register APNS...")
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
// user notifications auth
// all of this works for iOS 10+
let options: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, err) in
if let err = err {
print("Failed to request auth:", err)
return
}
if granted {
print("Auth granted.")
} else {
print("Auth denied.")
}
}
application.registerForRemoteNotifications()
}
}
|
b117c165315347a541ef4582d78c3f26
| 30.752577 | 205 | 0.741558 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
refs/heads/main
|
Buy/Generated/Storefront/CustomerActivatePayload.swift
|
mit
|
1
|
//
// CustomerActivatePayload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Return type for `customerActivate` mutation.
open class CustomerActivatePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CustomerActivatePayload
/// The customer object.
@discardableResult
open func customer(alias: String? = nil, _ subfields: (CustomerQuery) -> Void) -> CustomerActivatePayloadQuery {
let subquery = CustomerQuery()
subfields(subquery)
addField(field: "customer", aliasSuffix: alias, subfields: subquery)
return self
}
/// A newly created customer access token object for the customer.
@discardableResult
open func customerAccessToken(alias: String? = nil, _ subfields: (CustomerAccessTokenQuery) -> Void) -> CustomerActivatePayloadQuery {
let subquery = CustomerAccessTokenQuery()
subfields(subquery)
addField(field: "customerAccessToken", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func customerUserErrors(alias: String? = nil, _ subfields: (CustomerUserErrorQuery) -> Void) -> CustomerActivatePayloadQuery {
let subquery = CustomerUserErrorQuery()
subfields(subquery)
addField(field: "customerUserErrors", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `customerUserErrors` instead.")
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CustomerActivatePayloadQuery {
let subquery = UserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `customerActivate` mutation.
open class CustomerActivatePayload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CustomerActivatePayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "customer":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CustomerActivatePayload.self, field: fieldName, value: fieldValue)
}
return try Customer(fields: value)
case "customerAccessToken":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CustomerActivatePayload.self, field: fieldName, value: fieldValue)
}
return try CustomerAccessToken(fields: value)
case "customerUserErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CustomerActivatePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CustomerUserError(fields: $0) }
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CustomerActivatePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try UserError(fields: $0) }
default:
throw SchemaViolationError(type: CustomerActivatePayload.self, field: fieldName, value: fieldValue)
}
}
/// The customer object.
open var customer: Storefront.Customer? {
return internalGetCustomer()
}
func internalGetCustomer(alias: String? = nil) -> Storefront.Customer? {
return field(field: "customer", aliasSuffix: alias) as! Storefront.Customer?
}
/// A newly created customer access token object for the customer.
open var customerAccessToken: Storefront.CustomerAccessToken? {
return internalGetCustomerAccessToken()
}
func internalGetCustomerAccessToken(alias: String? = nil) -> Storefront.CustomerAccessToken? {
return field(field: "customerAccessToken", aliasSuffix: alias) as! Storefront.CustomerAccessToken?
}
/// The list of errors that occurred from executing the mutation.
open var customerUserErrors: [Storefront.CustomerUserError] {
return internalGetCustomerUserErrors()
}
func internalGetCustomerUserErrors(alias: String? = nil) -> [Storefront.CustomerUserError] {
return field(field: "customerUserErrors", aliasSuffix: alias) as! [Storefront.CustomerUserError]
}
/// The list of errors that occurred from executing the mutation.
@available(*, deprecated, message:"Use `customerUserErrors` instead.")
open var userErrors: [Storefront.UserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "customer":
if let value = internalGetCustomer() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAccessToken":
if let value = internalGetCustomerAccessToken() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerUserErrors":
internalGetCustomerUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
|
1ebdf2e10ee4cfc497c031a6bc4a7e1b
| 36.021505 | 136 | 0.729887 | false | false | false | false |
imzyf/99-projects-of-swift
|
refs/heads/master
|
015-stretchy-header/015-stretchy-header/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// 015-stretchy-header
//
// Created by moma on 2017/10/31.
// Copyright © 2017年 yifans. All rights reserved.
//
import UIKit
class ViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
@IBOutlet weak var headerImageView: UIImageView!
@IBOutlet weak var tableView: UITableView!
let datas = [
"when i was young",
"i'd listen to the radio",
"waiting for my favorite songs",
"when they played i'd sing along",
"it make me smile"
]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = datas[indexPath.row]
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 偏移量
let offsetY = scrollView.contentOffset.y
let tableHeight = tableView.frame.height
// 偏移比例
let validateOffsetY = -offsetY / tableHeight
let scaleFactor = 1 + validateOffsetY
// 0.6 - 1.3
print(scaleFactor)
headerImageView.transform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
db28c1ce93418e24ababc40351431001
| 26.359375 | 100 | 0.628 | false | false | false | false |
pierrewehbe/MyVoice
|
refs/heads/master
|
MyVoice/AudioObject.swift
|
mit
|
1
|
//
// AudioFile.swift
// MyVoice
//
// Created by Pierre on 12/28/16.
// Copyright © 2016 Pierre. All rights reserved.
//
import Foundation
class AudioObject {
var name : String
var duration : String
var dateOfCreation : String
var directory : String
var flags : [TimeInterval]
init(){
self.name = "NONAME"
self.duration = "00:00:00"
self.dateOfCreation = "Never Created"
self.directory = "DOESN'T EXIST"
self.flags = []
}
init(n: String, d: String , dof: String, dir: String , f : [TimeInterval]){
self.name = n
self.duration = d
self.dateOfCreation = dof
self.directory = dir
self.flags = f
}
func printInfo(){
print(name)
print(duration)
print(dateOfCreation)
print(directory)
print(flags)
}
}
|
8bf679452c5b57a75360ecd68d5e00ed
| 21.043478 | 79 | 0.491124 | false | false | false | false |
felipericieri/FRStretchImageView
|
refs/heads/master
|
FRStretchImageViewTests/FRStretchImageViewTests.swift
|
mit
|
1
|
//
// FRStretchImageViewTests.swift
// FRStretchImageViewTests
//
// Created by Felipe Ricieri on 11/03/17.
// Copyright © 2017 Ricieri Labs. All rights reserved.
//
import XCTest
@testable import FRStretchImageView
class FRStretchImageViewTests: XCTestCase {
fileprivate var image : FRStretchImageView!
fileprivate var scroll : UIScrollView!
fileprivate var contentView : UIView!
override func setUp() {
super.setUp()
// Frame
let frame = CGRect(
origin: CGPoint(x:0, y:0),
size: CGSize(width: 375, height: 667)
)
let imageHeight : CGFloat = 200
// Set up Scroll
scroll = UIScrollView(frame: frame)
// Set up Content View
contentView = UIView(frame: frame)
// Set up Image
image = FRStretchImageView(frame: frame)
// Prepare Scrollview
contentView.addSubview(image)
scroll.addSubview(contentView)
// Assert we do have outlets
XCTAssert(scroll != nil, "UIScrollView cannot be nil")
XCTAssert(image != nil, "UIImageView cannot be nil")
XCTAssert(contentView != nil, "Content View (UIView) cannot be nil")
// Set constraints
let topConstraint = NSLayoutConstraint(item: image, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let heightConstraint = NSLayoutConstraint(item: image, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 0.0, constant: imageHeight)
NSLayoutConstraint.activate([topConstraint, heightConstraint])
}
override func tearDown() {
self.image = nil
self.scroll = nil
self.contentView = nil
super.tearDown()
}
func testStretchHeightWhenPulledByScrollView() {
// Launch method
image.stretchHeightWhenPulledBy(scrollView: scroll)
// Assert
XCTAssert(scroll.clipsToBounds == false, "FRStretchImageView didn't set UIScrollView.clipToBounds to FALSE")
XCTAssert(image.topConstraint != nil, "FRStretchImageView Top Constraint cannot be nil.")
XCTAssert(image.heightConstraint != nil, "FRStretchImageView Height Constraint cannot be nil")
}
func testObserveValueForKeyPathContentOffset() {
// Assert outlets have relationship
XCTAssert(image.superview == contentView, "UIImageView must be child of Content View (UIView)")
XCTAssert(contentView.superview == scroll, "Content View (UIView) must be child of UIScrollView")
// Launch method
image.stretchHeightWhenPulledBy(scrollView: scroll)
// Initial state
let initialPosition = image.topConstraint.constant
let initialSize = image.heightConstraint.constant
let change : CGFloat = -300
// Change UIScrollView contentOffset
scroll.contentOffset = CGPoint(x: 0, y: -300)
// Assert changes
XCTAssert(image.heightConstraint.constant > initialSize, "UIImageView didn't changed height")
XCTAssert(image.topConstraint.constant < initialPosition, "UIImageView didn't changed position")
XCTAssert(image.heightConstraint.constant == initialSize + (-change), "UIImageView height must be equal (-\"change\")")
XCTAssert(image.topConstraint.constant == change, "UIImageView origin Y must be equal \"change\"")
// Return to 0
scroll.contentOffset = CGPoint(x: 0, y: 0)
// Assert changes
XCTAssert(image.heightConstraint.constant == initialSize, "UIImageView height must return to initial size")
XCTAssert(image.topConstraint.constant == initialPosition, "UIImageView origin Y must return to initial position")
}
}
|
6f301a2034034a253c947acd77a86c8d
| 38.831683 | 232 | 0.658712 | false | true | false | false |
ioscreator/ioscreator
|
refs/heads/master
|
SwiftUIRotateGestureTutorial/SwiftUIRotateGestureTutorial/SceneDelegate.swift
|
mit
|
1
|
//
// SceneDelegate.swift
// SwiftUIRotateGestureTutorial
//
// Created by Arthur Knopper on 27/10/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Get the managed object context from the shared persistent container.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
// Add `@Environment(\.managedObjectContext)` in the views that will need the context.
let contentView = ContentView().environment(\.managedObjectContext, context)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
|
5b59483417ccc6dc7409b2816f54db18
| 46.169014 | 147 | 0.71484 | false | false | false | false |
CatchChat/Yep
|
refs/heads/master
|
Yep/Views/PullToRefresh/YepRefreshView.swift
|
mit
|
1
|
//
// YepRefreshView.swift
// YepPullRefresh
//
// Created by kevinzhow on 15/4/14.
// Copyright (c) 2015年 kevinzhow. All rights reserved.
//
import UIKit
import QuartzCore
final class YepShape: CAShapeLayer {
let shapeColor = UIColor(red:0.33, green:0.71, blue:0.98, alpha:1)
func setupPathWithWidth(width: CGFloat, height: CGFloat) {
let rectanglePath = UIBezierPath()
let bottomGap = height / CGFloat(tan(M_PI / 3))
let bottomWidth = width - bottomGap * 2
//let gapSideLenth = bottomGap * 2
rectanglePath.moveToPoint(CGPointMake(0, 0))
rectanglePath.addLineToPoint(CGPointMake(width, 0))
rectanglePath.addLineToPoint(CGPointMake(width - bottomGap, height))
rectanglePath.addLineToPoint(CGPointMake(width - bottomWidth - bottomGap, height))
rectanglePath.closePath()
self.path = rectanglePath.CGPath
self.fillColor = shapeColor.CGColor
}
func setupFlipPathWithWidth(width: CGFloat, height: CGFloat) {
let rectanglePath = UIBezierPath()
let bottomGap = height / CGFloat(tan(M_PI / 3))
let bottomWidth = width - bottomGap * 2
//let gapSideLenth = bottomGap * 2
rectanglePath.moveToPoint(CGPointMake(bottomGap, 0))
rectanglePath.addLineToPoint(CGPointMake(bottomGap + bottomWidth, 0))
rectanglePath.addLineToPoint(CGPointMake(bottomGap + bottomWidth + bottomGap, height))
rectanglePath.addLineToPoint(CGPointMake(0, height))
rectanglePath.closePath()
self.path = rectanglePath.CGPath
self.fillColor = shapeColor.CGColor
}
}
final class YepRefreshView: UIView {
var shapes = [YepShape]()
var originShapePositions = [CGPoint]()
var ramdonShapePositions = [CGPoint]()
var isFlashing = false
let shapeWidth: CGFloat = 15
let shapeHeight: CGFloat = 4.0
override init(frame: CGRect) {
super.init(frame: frame)
//let x = shapeHeight / CGFloat(tan(M_PI / 3))
//var bottomWidth = shapeWidth - x * 2
let shape1 = YepShape()
let shape2 = YepShape()
let shape3 = YepShape()
let shape5 = YepShape()
let shape4 = YepShape()
let shape6 = YepShape()
shape1.setupPathWithWidth(shapeWidth, height: shapeHeight)
shape1.position = CGPoint(
x: shape1.position.x,
y: shape1.position.y + shapeHeight
)
shape2.setupFlipPathWithWidth(shapeWidth, height: shapeHeight)
shape3.setupPathWithWidth(shapeWidth, height: shapeHeight)
shape3.position = CGPoint(
x: shape3.position.x,
y: shape3.position.y + shapeHeight
)
shape4.setupFlipPathWithWidth(shapeWidth, height: shapeHeight)
shape5.setupPathWithWidth(shapeWidth, height: shapeHeight)
shape5.position = CGPoint(
x: shape5.position.x,
y: shape5.position.y + shapeHeight)
shape6.setupFlipPathWithWidth(shapeWidth, height: shapeHeight)
shapes = [shape1, shape2, shape3, shape4, shape5, shape6]
originShapePositions = shapes.map { $0.position }
ramdonShapePositions = generateRamdonShapePositionsWithCount(originShapePositions.count)
for (index, shape) in shapes.enumerate() {
shape.opacity = 0.0
shape.position = ramdonShapePositions[index]
}
let leafShape1 = CAShapeLayer()
leafShape1.frame = CGRect(
x: -shapeWidth / 2 + frame.width / 2,
y: -shapeHeight + frame.height / 2,
width: shapeWidth,
height: shapeHeight * 2
)
leafShape1.addSublayer(shape1)
leafShape1.addSublayer(shape2)
self.layer.addSublayer(leafShape1)
let leafShape2 = CAShapeLayer()
leafShape2.frame = CGRect(
x: -shapeWidth / 2 + frame.width / 2,
y: -shapeHeight + frame.height / 2,
width: shapeWidth,
height: shapeHeight * 2
)
leafShape2.addSublayer(shape3)
leafShape2.addSublayer(shape4)
self.layer.addSublayer(leafShape2)
let leafShape3 = CAShapeLayer()
leafShape3.frame = CGRect(
x: -shapeWidth / 2 + frame.width / 2,
y: -shapeHeight + frame.height / 2,
width: shapeWidth,
height: shapeHeight * 2
)
leafShape3.addSublayer(shape5)
leafShape3.addSublayer(shape6)
self.layer.addSublayer(leafShape3)
leafShape1.anchorPoint = CGPoint(x: 0, y: 0.5)
leafShape2.anchorPoint = CGPoint(x: 0, y: 0.5)
leafShape3.anchorPoint = CGPoint(x: 0, y: 0.5)
leafShape1.transform = CATransform3DMakeRotation(CGFloat(-M_PI / 6), 0.0, 0.0, 1.0)
leafShape2.transform = CATransform3DMakeRotation(CGFloat(M_PI / 2), 0.0, 0.0, 1.0)
leafShape3.transform = CATransform3DMakeRotation(CGFloat(-M_PI + M_PI / 6), 0.0, 0.0, 1.0)
}
func generateRamdonShapePositionsWithCount(count: Int) -> [CGPoint] {
func randomInRange(range: Range<Int>) -> CGFloat {
var offset = 0
if range.startIndex < 0 {
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return CGFloat(Int(mini + arc4random_uniform(maxi - mini)) - offset)
}
var positions = [CGPoint]()
for _ in 0..<count {
positions.append(CGPoint(x: randomInRange(-200...200), y: randomInRange(-200...200)))
}
return positions
}
func updateRamdonShapePositions() {
ramdonShapePositions = generateRamdonShapePositionsWithCount(ramdonShapePositions.count)
}
func updateShapePositionWithProgressPercentage(progressPercentage: CGFloat) {
if progressPercentage >= 1.0 {
if !isFlashing {
beginFlashing()
}
} else {
if isFlashing {
stopFlashing()
}
}
for (index, shape) in shapes.enumerate() {
shape.opacity = Float(progressPercentage)
let x1 = ramdonShapePositions[index].x
let y1 = ramdonShapePositions[index].y
let x0 = originShapePositions[index].x
let y0 = originShapePositions[index].y
shape.position = CGPoint(
x: x1 + (x0 - x1) * progressPercentage,
y: y1 + (y0 - y1) * progressPercentage
)
}
}
func beginFlashing() {
isFlashing = true
for (index, shape) in shapes.enumerate() {
shape.opacity = 1.0
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 1.0
animation.toValue = 0.5
animation.repeatCount = 1000
animation.autoreverses = true
animation.fillMode = kCAFillModeBoth
animation.timingFunction = CAMediaTimingFunction(name: "linear")
var delay: Double = 0
let timeScale: Double = 3
switch index {
case 0, 5:
delay = 0.1 * timeScale
case 1, 2:
delay = 0.05 * timeScale
default:
break
}
animation.duration = 0.09 * timeScale
animation.beginTime = CACurrentMediaTime() + delay
shape.addAnimation(animation, forKey: "flip")
}
}
func stopFlashing() {
isFlashing = false
for shape in shapes {
shape.removeAnimationForKey("flip")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
362e264145003ad990533da46e87c04a
| 29.346008 | 98 | 0.58727 | false | false | false | false |
flodolo/firefox-ios
|
refs/heads/main
|
Storage/FileAccessor.swift
|
mpl-2.0
|
2
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
/**
* A convenience class for file operations under a given root directory.
* Note that while this class is intended to be used to operate only on files
* under the root, this is not strictly enforced: clients can go outside
* the path using ".." or symlinks.
*/
open class FileAccessor {
public let rootPath: String
public init(rootPath: String) {
self.rootPath = rootPath
}
/**
* Gets the absolute directory path at the given relative path, creating it if it does not exist.
*/
open func getAndEnsureDirectory(_ relativeDir: String? = nil) throws -> String {
var absolutePath = rootPath
if let relativeDir = relativeDir {
absolutePath = URL(fileURLWithPath: absolutePath).appendingPathComponent(relativeDir).path
}
try createDir(absolutePath)
return absolutePath
}
/**
* Removes the file or directory at the given path, relative to the root.
*/
open func remove(_ relativePath: String) throws {
let path = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path
try FileManager.default.removeItem(atPath: path)
}
/**
* Removes the contents of the directory without removing the directory itself.
*/
open func removeFilesInDirectory(_ relativePath: String = "") throws {
let fileManager = FileManager.default
let path = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path
let files = try fileManager.contentsOfDirectory(atPath: path)
for file in files {
try remove(URL(fileURLWithPath: relativePath).appendingPathComponent(file).path)
}
return
}
/**
* Determines whether a file exists at the given path, relative to the root.
*/
open func exists(_ relativePath: String) -> Bool {
let path = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path
return FileManager.default.fileExists(atPath: path)
}
open func attributesForFileAt(relativePath: String) throws -> [FileAttributeKey: Any] {
return try FileManager.default.attributesOfItem(atPath: URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath).path)
}
/**
* Moves the file or directory to the given destination, with both paths relative to the root.
* The destination directory is created if it does not exist.
*/
open func move(_ fromRelativePath: String, toRelativePath: String) throws {
let rootPathURL = URL(fileURLWithPath: rootPath)
let fromPath = rootPathURL.appendingPathComponent(fromRelativePath).path
let toPath = rootPathURL.appendingPathComponent(toRelativePath)
let toDir = toPath.deletingLastPathComponent()
let toDirPath = toDir.path
try createDir(toDirPath)
try FileManager.default.moveItem(atPath: fromPath, toPath: toPath.path)
}
open func copyMatching(fromRelativeDirectory relativePath: String, toAbsoluteDirectory absolutePath: String, matching: (String) -> Bool) throws {
let fileManager = FileManager.default
let pathURL = URL(fileURLWithPath: rootPath).appendingPathComponent(relativePath)
let path = pathURL.path
let destURL = URL(fileURLWithPath: absolutePath, isDirectory: true)
let files = try fileManager.contentsOfDirectory(atPath: path)
for file in files {
if !matching(file) {
continue
}
let from = pathURL.appendingPathComponent(file, isDirectory: false).path
let to = destURL.appendingPathComponent(file, isDirectory: false).path
do {
try fileManager.copyItem(atPath: from, toPath: to)
} catch {
}
}
}
open func copy(_ fromRelativePath: String, toAbsolutePath: String) throws -> Bool {
let fromPath = URL(fileURLWithPath: rootPath).appendingPathComponent(fromRelativePath).path
let dest = URL(fileURLWithPath: toAbsolutePath).deletingLastPathComponent().path
try createDir(dest)
try FileManager.default.copyItem(atPath: fromPath, toPath: toAbsolutePath)
return true
}
/**
* Creates a directory with the given path, including any intermediate directories.
* Does nothing if the directory already exists.
*/
fileprivate func createDir(_ absolutePath: String) throws {
try FileManager.default.createDirectory(atPath: absolutePath, withIntermediateDirectories: true, attributes: nil)
}
}
|
4351b828dcdb4d933dc436a48e781d97
| 40 | 149 | 0.686888 | false | false | false | false |
mspvirajpatel/SwiftyBase
|
refs/heads/master
|
Example/SwiftyBase/Controller/ImageViewer/PhotoCollectionCell.swift
|
mit
|
1
|
//
// PhotoCollectionCell.swift
// SwiftyBase
//
// Created by MacMini-2 on 18/09/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import SwiftyBase
class PhotoCollectionCell: UICollectionViewCell {
// MARK: - Attributes -
var feedImageView:BaseImageView!
var baselayout:AppBaseLayout!
var parentTableView:UICollectionView!
var isCellSelected : Bool = false
@IBInspectable var FIRST: CGFloat = 1.5
@IBInspectable var parallaxRatio: CGFloat = 1.5 {
didSet {
self.parallaxRatio = max(parallaxRatio, 1.0)
self.parallaxRatio = min(parallaxRatio, 2.0)
var rect: CGRect = self.bounds
rect.size.height = rect.size.height * parallaxRatio
self.feedImageView.frame = rect
self.updateParallaxOffset()
}
}
// MARK: - Lifecycle -
override init(frame: CGRect)
{
super.init(frame: frame)
self.loadViewControls()
self.setViewControlsLayout()
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
self.safeRemoveObserver()
var v: UIView? = newSuperview
while (v != nil) {
if (v is UICollectionView) {
self.parentTableView = (v as? UICollectionView)
break
}
v = v?.superview
}
self.safeAddObserver()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
// MARK: - Layout -
func loadViewControls()
{
self.contentView.backgroundColor = UIColor.white
self.contentView.clipsToBounds = true
self.backgroundColor = UIColor.clear
self.clipsToBounds = true
self.setBorder(UIColor.red, width: 1.0, radius: 7.0)
/* feedImageView Allocation */
feedImageView = BaseImageView.init(type: BaseImageViewType.defaultImg, superView: self.contentView)
//feedImageView.setupForImageViewer()
feedImageView.contentMode = UIView.ContentMode.scaleAspectFill
feedImageView.setBorder(UIColor.red, width: 1.0, radius: 7.0)
}
func setViewControlsLayout()
{
baselayout = AppBaseLayout.init()
baselayout.expandView(feedImageView, insideView: self.contentView)
self.layoutIfNeeded()
}
// MARK: - Public Interface -
func displayImage(image:NSString)
{
if(image != ""){
// feedImageView.displayImageFromURL(image as String)
_ = feedImageView.setImageFromURL(image as String)
}
}
func safeAddObserver() {
if self.parentTableView != nil {
defer {
}
self.parentTableView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.new , NSKeyValueObservingOptions.old], context: nil)
}
}
func safeRemoveObserver() {
if (self.parentTableView != nil) {
defer {
self.parentTableView = nil
}
self.parentTableView.removeObserver(self, forKeyPath: "contentOffset", context: nil)
}
}
override func layoutSubviews(){
super.layoutSubviews()
self.parallaxRatio = FIRST;
}
deinit{
self.safeRemoveObserver()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "contentOffset") {
if !self.parentTableView.visibleCells.contains(self) || (self.parallaxRatio == 1.0) {
return
}
self.updateParallaxOffset()
}
}
func updateParallaxOffset() {
if(self.parentTableView != nil)
{
let contentOffset: CGFloat = self.parentTableView.contentOffset.y
let cellOffset: CGFloat = self.frame.origin.y - contentOffset
let percent: CGFloat = (cellOffset + self.frame.size.height) / (self.parentTableView.frame.size.height + self.frame.size.height)
let extraHeight: CGFloat = self.frame.size.height * (self.parallaxRatio - 1.0)
var rect: CGRect = self.feedImageView.frame
rect.origin.y = -extraHeight * percent
self.feedImageView.frame = rect
}
}
// MARK: - User Interaction -
// MARK: - Internal Helpers -
}
|
51e4d5a5067855099d27afe7ca6efc99
| 28.605096 | 169 | 0.592298 | false | false | false | false |
paulz/PerspectiveTransform
|
refs/heads/master
|
Example/PerspectiveTransform/Visual.playground/Sources/QuadrilateralCalc.swift
|
mit
|
1
|
import UIKit
public class QuadrilateralCalc {
public init() {}
public var topLeft = CGPoint.zero
public var topRight = CGPoint.zero
public var bottomLeft = CGPoint.zero
public var bottomRight = CGPoint.zero
public func box() -> CGRect {
let xmin = min(min(min(topRight.x, topLeft.x), bottomLeft.x), bottomRight.x)
let ymin = min(min(min(topRight.y, topLeft.y), bottomLeft.y), bottomRight.y)
let xmax = max(max(max(topRight.x, topLeft.x), bottomLeft.x), bottomRight.x)
let ymax = max(max(max(topRight.y, topLeft.y), bottomLeft.y), bottomRight.y)
return CGRect(origin: CGPoint(x: xmin, y: ymin), size: CGSize(width: xmax - xmin, height: ymax - ymin))
}
public func modifyPoints(transform: (CGPoint) -> CGPoint) {
topLeft = transform(topLeft)
topRight = transform(topRight)
bottomLeft = transform(bottomLeft)
bottomRight = transform(bottomRight)
}
public func transformToFit(bounds: CGRect, anchorPoint: CGPoint) -> CATransform3D {
let boundingBox = box()
let frameTopLeft = boundingBox.origin
let quad = QuadrilateralCalc()
quad.topLeft = CGPoint(x: topLeft.x-frameTopLeft.x, y: topLeft.y-frameTopLeft.y)
quad.topRight = CGPoint(x: topRight.x-frameTopLeft.x, y: topRight.y-frameTopLeft.y)
quad.bottomLeft = CGPoint(x: bottomLeft.x-frameTopLeft.x, y: bottomLeft.y-frameTopLeft.y)
quad.bottomRight = CGPoint(x: bottomRight.x-frameTopLeft.x, y: bottomRight.y-frameTopLeft.y)
let transform = rectToQuad(rect: bounds, quad: quad)
let anchorOffset = CGPoint(x: anchorPoint.x - boundingBox.origin.x, y: anchorPoint.y - boundingBox.origin.y)
let transPos = CATransform3DMakeTranslation(anchorOffset.x, anchorOffset.y, 0)
let transNeg = CATransform3DMakeTranslation(-anchorOffset.x, -anchorOffset.y, 0)
let fullTransform = CATransform3DConcat(CATransform3DConcat(transPos, transform), transNeg)
return fullTransform
}
public func rectToQuad(rect: CGRect, quad: QuadrilateralCalc) -> CATransform3D {
let x1a = quad.topLeft.x
let y1a = quad.topLeft.y
let x2a = quad.topRight.x
let y2a = quad.topRight.y
let x3a = quad.bottomLeft.x
let y3a = quad.bottomLeft.y
let x4a = quad.bottomRight.x
let y4a = quad.bottomRight.y
let X = rect.origin.x
let Y = rect.origin.y
let W = rect.size.width
let H = rect.size.height
let y21 = y2a - y1a
let y32 = y3a - y2a
let y43 = y4a - y3a
let y14 = y1a - y4a
let y31 = y3a - y1a
let y42 = y4a - y2a
let a = -H*(x2a*x3a*y14 + x2a*x4a*y31 - x1a*x4a*y32 + x1a*x3a*y42)
let b = W*(x2a*x3a*y14 + x3a*x4a*y21 + x1a*x4a*y32 + x1a*x2a*y43)
let c = H*X*(x2a*x3a*y14 + x2a*x4a*y31 - x1a*x4a*y32 + x1a*x3a*y42) - H*W*x1a*(x4a*y32 - x3a*y42 + x2a*y43) - W*Y*(x2a*x3a*y14 + x3a*x4a*y21 + x1a*x4a*y32 + x1a*x2a*y43)
let d = H*(-x4a*y21*y3a + x2a*y1a*y43 - x1a*y2a*y43 - x3a*y1a*y4a + x3a*y2a*y4a)
let e = W*(x4a*y2a*y31 - x3a*y1a*y42 - x2a*y31*y4a + x1a*y3a*y42)
let f1 = (x4a*(Y*y2a*y31 + H*y1a*y32) - x3a*(H + Y)*y1a*y42 + H*x2a*y1a*y43 + x2a*Y*(y1a - y3a)*y4a + x1a*Y*y3a*(-y2a + y4a))
let f2 = x4a*y21*y3a - x2a*y1a*y43 + x3a*(y1a - y2a)*y4a + x1a*y2a*(-y3a + y4a)
let f = -(W*f1 - H*X*f2)
let g = H*(x3a*y21 - x4a*y21 + (-x1a + x2a)*y43)
let h = W*(-x2a*y31 + x4a*y31 + (x1a - x3a)*y42)
let temp = X * (-x3a*y21 + x4a*y21 + x1a*y43 - x2a*y43) + W * (-x3a*y2a + x4a*y2a + x2a*y3a - x4a*y3a - x2a*y4a + x3a*y4a)
var i = W * Y * (x2a*y31 - x4a*y31 - x1a*y42 + x3a*y42) + H * temp
let kEpsilon = CGFloat(0.0001)
if abs(i) < kEpsilon {
i = kEpsilon * (i > 0 ? 1.0 : -1.0)
}
return CATransform3D(m11: a/i, m12: d/i, m13: 0, m14: g/i,
m21: b/i, m22: e/i, m23: 0, m24: h/i,
m31: 0, m32: 0, m33: 1, m34: 0,
m41: c/i, m42: f/i, m43: 0, m44: 1.0)
}
}
|
6d7858285f44a62c5f2ce83e2c6b49ec
| 41.979381 | 177 | 0.590789 | false | false | false | false |
bumpersfm/handy
|
refs/heads/master
|
Components/CustomTitleView.swift
|
mit
|
1
|
//
// Created by Dani Postigo on 11/24/16.
//
import Foundation
import UIKit
public class CustomTitleView: ControlBar {
public let textLabel = UILabel(title: "Title", color: UIColor.whiteColor(), font: UIFont.boldSystemFontOfSize(24.0))
public let detailTextLabel = UILabel(title: "Subtitle", color: UIColor.whiteColor(), font: UIFont.boldSystemFontOfSize(12.0))
override public init(frame: CGRect) {
super.init(frame: frame)
self.textLabel.textAlignment = .Left
self.textLabel.setContentHuggingPriority(1000, forAxis: .Vertical)
self.textLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
self.textLabel.numberOfLines = 1
self.detailTextLabel.textAlignment = .Left
self.detailTextLabel.setContentHuggingPriority(1000, forAxis: .Vertical)
self.detailTextLabel.setContentCompressionResistancePriority(1000, forAxis: .Horizontal)
let stack = UIStackView(axis: .Vertical)
stack.addArrangedSubviews([self.textLabel, self.detailTextLabel])
stack.preservesSuperviewLayoutMargins = true
stack.layoutMarginsRelativeArrangement = true
self.translatesAutoresizingMaskIntoConstraints = false
self.titleView = stack
self.layoutIfNeeded()
self.translatesAutoresizingMaskIntoConstraints = true
}
required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
// MARK: Convenience
public convenience init(title: String, subtitle: String = "Subtitle") {
self.init(); self.title = title; self.subtitle = subtitle
}
public convenience init(navigationItem: UINavigationItem) {
self.init(title: navigationItem.title ?? "")
}
public convenience init(forViewController vc: UIViewController) {
self.init(navigationItem: vc.navigationItem)
let estimatedItemWidth: CGFloat = 50
let target = CGSize(width: vc.view.frame.size.width - (estimatedItemWidth * 2), height: self.titleView.frame.size.height)
self.textLabel.preferredMaxLayoutWidth = target.width
let fittingSize = self.titleView.systemLayoutSizeFittingSize(target, withHorizontalFittingPriority: UILayoutPriorityRequired, verticalFittingPriority: UILayoutPriorityRequired)
self.frame.size.width = fittingSize.width
}
public var title: String? {
set { self.textLabel.text = newValue }
get { return self.textLabel.text }
}
public var subtitle: String? {
set { self.detailTextLabel.text = newValue }
get { return self.detailTextLabel.text }
}
}
extension UIView {
func systemLayout() {
let frame = self.frame
let compressedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
Swift.print("compressedSize = \(compressedSize)")
assert(self.frame == frame)
let expandedSize = self.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize)
Swift.print("expandedSize = \(expandedSize)")
assert(self.frame == frame)
}
}
|
6df530a4e83c12b5137885e1e6bd66e4
| 37.180723 | 184 | 0.688447 | false | false | false | false |
zadr/conservatory
|
refs/heads/main
|
Code/Inputs/Cocoa/CGImageBridging.swift
|
bsd-2-clause
|
1
|
import CoreGraphics
import ImageIO
#if os(iOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
extension CGImage: ImageViewable {
private func data(_ format: CFString) -> UnsafePointer<UInt8> {
let data = CFDataCreateMutable(nil, 0)
let destination = CGImageDestinationCreateWithData(data!, format, 1, nil)!
CGImageDestinationAddImage(destination, self, nil)
CGImageDestinationFinalize(destination)
return CFDataGetBytePtr(data)
}
public var bitmapView: UnsafePointer<UInt8> {
return data(kUTTypeBMP)
}
public var JPEGView: UnsafePointer<UInt8> {
return data(kUTTypeJPEG)
}
public var PNGView: UnsafePointer<UInt8> {
return data(kUTTypePNG)
}
}
extension Image {
public init(image: CGImage) {
// todo: support non-RGBA pixel ordering so these preconditions can go away
precondition(image.colorSpace?.model == .rgb, "Unable to initalize Image with non-RGB images")
precondition(image.alphaInfo == .premultipliedLast, "Unable to initalize Image without alpha component at end")
let data = image.dataProvider?.data
let bytes = CFDataGetBytePtr(data)
let size = Size(width: image.width, height: image.height)
self.init(data: bytes!, size: size)
}
}
public extension Image {
internal var CGImageView: CGImage {
let bytes = UnsafeMutableRawPointer(mutating: storage)
let context = CGContext(data: bytes, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 4 * Int(size.width), space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
return context!.makeImage()!
}
}
|
4d8cf37c0bf937ff90112bfbc1e9f8e5
| 30.529412 | 238 | 0.761816 | false | false | false | false |
Joachimdj/JobResume
|
refs/heads/master
|
Apps/Kort sagt/KortSagt-master/KortSagt/TableViewController.swift
|
mit
|
1
|
import UIKit
import Alamofire
import SwiftyJSON
var selectedVideo = 0;
var videos = [Video]()
// filtered search results
var filteredVideos = [Video]()
var is_searching:Bool!
class TableViewController: UITableViewController {
var refreshCtrl = UIRefreshControl()
var loadingStatus = false
var nextPageToken = "";
var prevPageToken = "";
var alreadyRunned = false
@IBOutlet weak var search: UISearchBar!
@IBOutlet var table: UITableView!
func loadNewVideo1(){
if(nextPageToken == ""){
videos.removeAll()
filteredVideos.removeAll()
}
let url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCBBSZunZagb4bDBi3PSqd7Q&order=date&key=AIzaSyA0T0fCHDyQzKCH0z0xs-i8Vh6DeSMcUuQ&maxResults=50&part=snippet,contentDetails&pageToken=\(nextPageToken)"
Alamofire.request(.GET, url,encoding: .URLEncodedInURL).responseJSON { response in
switch response.result {
case .Success(let data):
let json = JSON(data)
_ = json["items"]
let count = json["items"].count;
for var i = 0; i <= count; i++
{
if(json["items"][i]["id"]["videoId"] != nil){
videos.append(Video(id:json["items"][i]["id"]["videoId"].string! ,
name:json["items"][i]["snippet"]["title"].string!,
desc:json["items"][i]["snippet"]["description"].string!))
}
print(" \(i) = \(count)")
}
if(json["prevPageToken"] != nil){self.prevPageToken = json["prevPageToken"].string! }
if(json["nextPageToken"] != nil){ self.nextPageToken = json["nextPageToken"].string! }
if(json["nextPageToken"].string != nil) {
self.loadNewVideo1()
}
if(self.table != nil){self.refreshCtrl.endRefreshing()
self.table.reloadData()
self.nextPageToken = ""
is_searching = false
self.searchBarSearchButtonClicked(self.search)
}
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
_ = self.search.text
is_searching = false
isPresented = false
self.refreshCtrl.endRefreshing()
refreshCtrl.addTarget(self, action: "loadNewVideo1", forControlEvents: .ValueChanged)
tableView?.addSubview(refreshCtrl)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if is_searching == true{
return filteredVideos.count
}else{
return videos.count //Currently Giving default Value
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) //1
var idString = ""
if is_searching == true{
idString = "https://i.ytimg.com/vi/\(filteredVideos[indexPath.row].id)/hqdefault.jpg"
}
else
{idString = "https://i.ytimg.com/vi/\(videos[indexPath.row].id)/hqdefault.jpg"
}
if(idString != ""){
let imageView = UIImageView(frame: CGRectMake(0, -1, cell.frame.width, cell.frame.height))
_ = NSURL(string: idString)
ImageLoader.sharedLoader.imageForUrl(idString, completionHandler:{(image: UIImage?, url: String) in
imageView.image = Toucan(image: image!).resize(CGSize(width: 640, height: 360), fitMode: Toucan.Resize.FitMode.Crop).image
})
cell.backgroundView = imageView;
}
return cell
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedVideo = indexPath.row
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let modalVC: ItemViewController = storyboard.instantiateViewControllerWithIdentifier("item") as! ItemViewController
let navController = UINavigationController(rootViewController: modalVC)
// self.animator = ARNModalTransitonAnimator(modalViewController: navController)
//
// self.animator!.transitionDuration = 0.7
// self.animator!.direction = .Bottom
// navController.transitioningDelegate = self.animator!
self.presentViewController(navController, animated: true, completion: nil)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
if searchBar.text!.isEmpty{
is_searching = false
tableView.reloadData()
} else {
print("search text %@ ",searchBar.text! as NSString)
is_searching = true
filteredVideos.removeAll()
for var index = 0; index < videos.count; index++
{
let currentString = "\(videos[index].name) \(videos[index].desc)"
if currentString.lowercaseString.rangeOfString(searchText.lowercaseString) != nil {
print(videos[index].name)
filteredVideos.append(videos[index])
}
}
tableView.reloadData()
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
NSLog("The default search bar keyboard search button was tapped: \(searchBar.text).")
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
NSLog("The default search bar cancel button was tapped.")
searchBar.resignFirstResponder()
}
}
|
a36ef54e8b79699f76ac5c4bf3297bb4
| 34.04712 | 236 | 0.558112 | false | false | false | false |
tomomura/TimeSheet
|
refs/heads/master
|
Classes/Controllers/Intros/FTIntrosInputInitialDataViewController.swift
|
mit
|
1
|
//
// FTIntrosInputInitialDataViewController.swift
// TimeSheet
//
// Created by TomomuraRyota on 2015/04/27.
// Copyright (c) 2015年 TomomuraRyota. All rights reserved.
//
import UIKit
class FTIntrosInputInitialDataViewController: FTIntrosPageDataViewController, UITextFieldDelegate {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
// MARK: - View Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
self.pageIndex = 1
self.descriptionLabel.text = "名前を入力したらすぐにはじめられます"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - UITextField Delegate
/**
入力文字の最大文字数を10文字に制限し、10文字以内であれば値を設定
:param: textField <#textField description#>
:param: range <#range description#>
:param: string <#string description#>
:returns: <#return value description#>
*/
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let str = textField.text as NSString
let inputedStr = str.stringByReplacingCharactersInRange(range, withString: string)
if count(inputedStr) > 10 {
return false
} else {
self.user!.name = inputedStr
return true
}
}
}
|
ee96351e4d532d5d1b72e39a2bea42e4
| 27.44 | 132 | 0.654712 | false | false | false | false |
DasHutch/minecraft-castle-challenge
|
refs/heads/develop
|
app/_src/ChallengeRulesAndStages.swift
|
gpl-2.0
|
1
|
//
// ChallengeRulesAndStages.swift
// MC Castle Challenge
//
// Created by Gregory Hutchinson on 8/29/15.
// Copyright © 2015 Gregory Hutchinson. All rights reserved.
//
import UIKit
class ChallengeRulesAndStages: BaseTableViewController {
@IBOutlet weak var objectiveAndPlotStaticCellLabel: UILabel!
@IBOutlet weak var rulesStaticCellLabel: UILabel!
@IBOutlet weak var woodenAgeStaticCellLabel: UILabel!
@IBOutlet weak var stoneAgeStaticCellLabel: UILabel!
@IBOutlet weak var ironAgeStaticCellLabel: UILabel!
@IBOutlet weak var goldAgeStaticCellLabel: UILabel!
@IBOutlet weak var diamondAgeStaticCellLabel: UILabel!
private struct ChallengeRulesAndStagesTableViewSections {
static let HowToPlay = 0
static let Stages = 1
}
var selectedStage: ChallengeStages?
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configTableView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUI()
}
override func contentSizeDidChange(newUIContentSizeCategoryNewValueKey: String) {
updateUI()
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == SegueIdentifiers.showAge {
if let vc = segue.destinationViewController.contentViewController as? DetailViewManagerViewController {
guard let stage = selectedStage else {
log.warning("Attempting to prepare \(SegueIdentifiers.showAge) segue but no age was selected")
return
}
vc.detailView = DetailViewManagerViewController.DetailViewType.age(stage: stage)
}else {
log.warning("Attempting to prepare \(SegueIdentifiers.showAge) segue but found an unexpected ViewController: \(segue.destinationViewController)")
}
}else if segue.identifier == SegueIdentifiers.showObjective {
if let vc = segue.destinationViewController.contentViewController as? DetailViewManagerViewController {
vc.detailView = DetailViewManagerViewController.DetailViewType.objectives
}else {
log.warning("Attempting to prepare \(SegueIdentifiers.showObjective) segue but found an unexpected ViewController: \(segue.destinationViewController)")
}
}else if segue.identifier == SegueIdentifiers.showRules {
print("kdsajgkl;dsahgasdklghsadl;kgjdsakl;")
if let vc = segue.destinationViewController.contentViewController as? DetailViewManagerViewController {
vc.detailView = DetailViewManagerViewController.DetailViewType.rules
}else {
log.warning("Attempting to prepare \(SegueIdentifiers.showRules) segue but found an unexpected ViewController: \(segue.destinationViewController)")
}
}else {
log.warning("Attempting to prepare for an unknown segue identifier: \(segue.identifier)")
}
}
// MARK: - Private
private func configTableView() {
//????: Seems that setting this from the tableView.rowHeight as exists
// in storyboard doesn't actually trigger Autolayout / Self Sizing
tableView.estimatedRowHeight = 44.0 //tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorInset = UIEdgeInsetsZero
}
private func updateUI() {
objectiveAndPlotStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
rulesStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
woodenAgeStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
stoneAgeStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
ironAgeStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
goldAgeStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
diamondAgeStaticCellLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleTitle2)
}
}
// MARK: - UITableViewDelegate
extension ChallengeRulesAndStages {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard let cell = tableView.cellForRowAtIndexPath(indexPath) else {
log.severe("No Cell available for IndexPath: \(indexPath)")
return
}
if indexPath.section == ChallengeRulesAndStagesTableViewSections.HowToPlay {
//NOTE: Let the Segue in Storyboard do its thing...
}else if indexPath.section == ChallengeRulesAndStagesTableViewSections.Stages {
switch(indexPath.row) {
case ChallengeStages.WoodenAge.rawValue:
selectedStage = .WoodenAge
case ChallengeStages.StoneAge.rawValue:
selectedStage = .StoneAge
case ChallengeStages.IronAge.rawValue:
selectedStage = .IronAge
case ChallengeStages.GoldAge.rawValue:
selectedStage = .GoldAge
case ChallengeStages.DiamondAge.rawValue:
selectedStage = .DiamondAge
default:
log.warning("Attempting to select unknown stage for IndexPath: \(indexPath)")
selectedStage = nil
break
}
performSegueWithIdentifier(SegueIdentifiers.showAge, sender: cell)
}else {
log.error("Unknown TableView Section - cell selected, unable to perform segue.")
}
}
}
|
77f70d9c5b83082d1cb0968455d7ebd0
| 41.941606 | 167 | 0.674826 | false | false | false | false |
psoamusic/PourOver
|
refs/heads/master
|
PourOver/POPieceTableViewController.swift
|
gpl-3.0
|
1
|
//
// POPresetTableViewController.swift
// PourOver
//
// Created by kevin on 6/19/16.
// Copyright © 2016 labuser. All rights reserved.
//
import UIKit
class POPieceTableViewController: POTableViewController, UINavigationControllerDelegate {
//===================================================================================
//MARK: Private Properties
//===================================================================================
private var selectedPieceIndexPath: NSIndexPath?
private var pieceDetailViewController: POPieceDetailViewController?
internal var reminderTextViewText: String {
get {
return ""
}
}
lazy internal var reminderTextView: UITextView? = {
let textView = UITextView(frame: CGRect(x: 10, y: 0, width: CGRectGetWidth(self.view.bounds) - 20, height: 210))
textView.textAlignment = .Center
textView.textColor = UIColor.interfaceColorDark()
textView.backgroundColor = UIColor.clearColor()
textView.font = UIFont.lightAppFontOfSize(20)
textView.userInteractionEnabled = false
return textView
}()
//===================================================================================
//MARK: View Lifecycle
//===================================================================================
override func viewDidLoad() {
super.viewDidLoad()
addDefaultBackButton()
if let _ = title {
addDefaultTitleViewWithText(title!)
}
rightTitleButton = UIButton(type: .Custom)
rightTitleButton?.setImage(UIImage(named: "refresh-button.png")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
navigationController?.delegate = self
refreshPieces()
}
//===================================================================================
//MARK: Interface
//===================================================================================
override func rightButtonTouchUpInside(sender: UIButton) {
closePieceAndRefreshPieceListWithCompletion({
//then reload the table
self.refreshPieces()
self.tableView.reloadData()
self.pieceDetailViewController?.removeFromParentViewController()
self.pieceDetailViewController = nil
})
}
//===================================================================================
//MARK: Refresh
//===================================================================================
internal func closePieceAndRefreshPieceListWithCompletion(completion: (() -> ())?) {
//first close the current file
if let appDelegate = UIApplication.sharedApplication().delegate as? POAppDelegate {
appDelegate.controllerCoordinator.stopUpdatingGenerators()
appDelegate.controllerCoordinator.cleanupGenerators()
POPdFileLoader.sharedPdFileLoader.closePdFile() {
completion?()
}
}
}
internal func refreshPieces() {
//implemented by children to refresh cellDictionaries
}
internal func checkForNoDocuments() {
if cellDictionaries.count <= 2 {
middleCellHighlightView.hidden = true
addNoDocumentsReminders()
}
else {
middleCellHighlightView.hidden = false
removeNoDocumentsReminders()
}
}
//===================================================================================
//MARK: Table View Delegate Methods
//===================================================================================
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
super.tableView(tableView, didSelectRowAtIndexPath: indexPath)
if let currentMiddleIndexPath = self.indexPathForCentermostCellInTableview(tableView) {
if indexPath == currentMiddleIndexPath {
//middle cell selected for playback
//transition to zoomed in, load pd patch, etc.
//insert detail view controller and animate in:
if pieceDetailViewController?.title != cellDictionaries[indexPath.row]["title"] as? String {
if let appDelegate = UIApplication.sharedApplication().delegate as? POAppDelegate {
appDelegate.controllerCoordinator.stopUpdatingGenerators()
appDelegate.controllerCoordinator.cleanupGenerators()
POPdFileLoader.sharedPdFileLoader.closePdFile() {
//instantiate pieceDetailViewController and push it onto the navigation controller stack
//once the transition is complete, the UINavigationController delegate method didShowViewController:animated: will load the Pd patch
self.pieceDetailViewController = nil
self.pieceDetailViewController = POPieceDetailViewController()
self.pieceDetailViewController!.pieceTitle = self.cellDictionaries[indexPath.row]["title"] as? String
if let defaultLength = self.cellDictionaries[indexPath.row]["defaultLength"] as? Double {
self.pieceDetailViewController!.defaultLength = NSTimeInterval(Int(defaultLength))
}
//store selected indexPath for loading on successful view controller push did finish
self.selectedPieceIndexPath = indexPath
self.navigationController?.pushViewController(self.pieceDetailViewController!, animated: true)
}
}
}
else {
//do not re-load the patch
selectedPieceIndexPath = nil
navigationController?.pushViewController(pieceDetailViewController!, animated: true)
}
}
}
//always deselect
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
//===================================================================================
//MARK: Layout
//===================================================================================
internal func addNoDocumentsReminders() {
if reminderTextView?.superview == nil {
reminderTextView?.text = reminderTextViewText
reminderTextView?.sizeToFit()
reminderTextView?.center = CGPoint(x: CGRectGetWidth(view.bounds) / 2.0, y: CGRectGetHeight(view.bounds) / 2.0)
if let _ = reminderTextView {
view.addSubview(reminderTextView!)
}
}
}
internal func removeNoDocumentsReminders() {
reminderTextView?.removeFromSuperview()
}
//===================================================================================
//MARK: UINavigationControllerDelegate
//===================================================================================
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
}
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
if viewController is POPieceDetailViewController {
//load selected file
if let indexPath = selectedPieceIndexPath {
if let filePath = cellDictionaries[indexPath.row]["filePath"] as? String {
let success = POPdFileLoader.sharedPdFileLoader.loadPdFileAtPath(filePath)
if !success {
return
}
}
}
}
}
}
|
006c62df24a8ab1c2ed69322f96d2961
| 43.293478 | 160 | 0.519141 | false | false | false | false |
maranathApp/GojiiFramework
|
refs/heads/master
|
GojiiFrameWork/DictionaryExtensions.swift
|
mit
|
1
|
//
// CGFloatExtensions.swift
// GojiiFrameWork
//
// Created by Stency Mboumba on 01/06/2017.
// Copyright © 2017 Stency Mboumba. All rights reserved.
//
import Foundation
/* --------------------------------------------------------------------------- */
// MARK: - Extension Dictionnary
/* --------------------------------------------------------------------------- */
public extension Dictionary {
/* --------------------------------------------------------------------------- */
// MARK: - Dictionnary → To
/* --------------------------------------------------------------------------- */
/**
Returns each element of the sequence in an array
:returns: Each element of the sequence in an array
*/
public func toArray () -> [Element] {
return self.map({ $0 })
}
/* --------------------------------------------------------------------------- */
// MARK: - Dictionnary → File
/* --------------------------------------------------------------------------- */
/**
Loads a JSON file from the app bundle into a new dictionary
- parameter filename: File name
- throws: BSError : PathForResource / NSData / JSON
- returns: Dictionary<String, AnyObject>
*/
public static func loadJSONFromBundle(filename: String) throws -> Dictionary<String, AnyObject> {
guard let path = Bundle.main.path(forResource: filename, ofType: "json") else {
throw DictionaryBSError.Nil(error: "[->pathForResource] The file could not be located\nFile : '\(filename).json'")
}
guard let data = try? NSData(contentsOfFile: path, options:.uncached) else {
throw DictionaryBSError.NSData(error:"[->NSData] The absolute path of the file not find\nFile : '\(filename)'")
}
guard let jsonDict = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? Dictionary<String, AnyObject> else {
throw DictionaryBSError.JSON(error: "[->NSJSONSerialization]Error.InvalidJSON Level file '\(filename)' is not valid JSON")
}
return jsonDict
}
/**
Load a Plist file from the app bundle into a new dictionary
:param: File name
:return: Dictionary<String, AnyObject>?
*/
/**
Load a Plist file from the app bundle into a new dictionary
- parameter filename: File name
- throws: BSError : Nil
- returns: Dictionary<String, AnyObject>
*/
public static func loadPlistFromBundle(filename: String) throws -> Dictionary<String, AnyObject> {
guard let path = Bundle.main.path(forResource: filename, ofType: "plist") else {
throw DictionaryBSError.Nil(error: "(pathForResource) The file could not be located\nFile : '\(filename).plist'")
}
guard let plistDict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> else {
throw DictionaryBSError.Nil(error: "(There is a file error or if the contents of the file are an invalid representation of a dictionary. File : '\(filename)'.plist")
}
return plistDict
}
}
/* --------------------------------------------------------------------------- */
// MARK: - Dictionnary BSError
/* --------------------------------------------------------------------------- */
/**
Enum for Debug DictionaryBSError
- Error: Error of any kind
- Nil: Error Nil Object
- NSData: Error NSData
- NSURL: Error NSUrl
- JSON: Error JSon
*/
public enum DictionaryBSError: Error, CustomStringConvertible {
case Error(error:String)
case Nil(error:String)
case NSData(error:String)
case NSURL(error:String)
case JSON(error:String)
/// A textual representation / Mark CustomStringConvertible
public var description: String {
switch self {
case .Error(let errorString) : return "\(errorString)"
case .Nil(let errorString) : return "\(errorString)"
case .NSData(let errorString) : return "\(errorString)"
case .NSURL(let errorString) : return "\(errorString)"
case .JSON(let errorString) : return "\(errorString)"
}
}
/**
Print Error
*/
// func print() { printObject("[BSFramework][Dictionnary extension] \(self.description)") }
}
|
b667bfb29aba7efebfe3f8a306e1529d
| 35.552 | 177 | 0.517619 | false | false | false | false |
gvsucis/mobile-app-dev-book
|
refs/heads/master
|
iOS/ch08/TraxyApp/TraxyApp/UIViewController+Validation.swift
|
gpl-3.0
|
6
|
//
// UIViewController+Validation.swift
// TraxyApp
//
// Created by Jonathan Engelsma on 2/7/17.
// Copyright © 2017 Jonathan Engelsma. All rights reserved.
//
import UIKit
extension UIViewController {
func isValidPassword(password: String?) -> Bool
{
guard let s = password, s.lowercased().range(of: "traxy") != nil else {
return false
}
return true
}
func isEmptyOrNil(password: String?) -> Bool
{
guard let s = password, s != "" else {
return false
}
return true
}
func isValidEmail(emailStr : String? ) -> Bool
{
var emailOk = false
if let email = emailStr {
let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", regex)
emailOk = emailPredicate.evaluate(with: email)
}
return emailOk
}
func reportError(msg: String) {
let alert = UIAlertController(title: "Failed", message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
|
b5244c780641fb366fa6ac494b5c24cd
| 26.844444 | 92 | 0.569034 | false | false | false | false |
Johennes/firefox-ios
|
refs/heads/master
|
Client/Frontend/Settings/SettingsTableViewController.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Shared
import UIKit
import XCGLogger
// The following are only here because we use master for L10N and otherwise these strings would disappear from the v1.0 release
private let Bug1204635_S1 = NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.")
private let Bug1204635_S2 = NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything")
private let Bug1204635_S3 = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
private let Bug1204635_S4 = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting: NSObject {
private var _title: NSAttributedString?
weak var delegate: SettingsDelegate?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: NSURL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
private(set) var accessibilityIdentifier: String?
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
var textAlignment: NSTextAlignment { return .Natural }
private(set) var enabled: Bool = true
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.detailTextLabel?.numberOfLines = 0
cell.textLabel?.attributedText = title
cell.textLabel?.textAlignment = textAlignment
cell.textLabel?.numberOfLines = 0
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.selectionStyle = enabled ? .Default : .None
cell.accessibilityIdentifier = accessibilityIdentifier
if let title = title?.string {
if let detailText = cell.detailTextLabel?.text {
cell.accessibilityLabel = "\(title), \(detailText)"
} else if let status = status?.string {
cell.accessibilityLabel = "\(title), \(status)"
} else {
cell.accessibilityLabel = title
}
}
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.indentationWidth = 0
cell.layoutMargins = UIEdgeInsetsZero
// So that the separator line goes all the way to the left edge.
cell.separatorInset = UIEdgeInsetsZero
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self._title = title
self.delegate = delegate
self.enabled = enabled ?? true
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection: Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count += 1
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i += 1
}
}
return nil
}
}
private class PaddedSwitch: UIView {
private static let Padding: CGFloat = 8
init(switchView: UISwitch) {
super.init(frame: CGRectZero)
addSubview(switchView)
frame.size = CGSizeMake(switchView.frame.width + PaddedSwitch.Padding, switchView.frame.height)
switchView.frame.origin = CGPointMake(PaddedSwitch.Padding, 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
let prefKey: String
private let prefs: Prefs
private let defaultValue: Bool
private let settingDidChange: ((Bool) -> Void)?
private let statusText: NSAttributedString?
init(prefs: Prefs, prefKey: String, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = attributedStatusText
super.init(title: attributedTitleText)
}
convenience init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
var statusTextAttributedString: NSAttributedString?
if let statusTextString = statusText {
statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor])
}
self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange)
}
override var status: NSAttributedString? {
return statusText
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: #selector(BoolSetting.switchValueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? defaultValue
if let title = title {
if let status = status {
control.accessibilityLabel = "\(title.string), \(status.string)"
} else {
control.accessibilityLabel = title.string
}
cell.accessibilityLabel = nil
}
cell.accessoryView = PaddedSwitch(switchView: control)
cell.selectionStyle = .None
}
@objc func switchValueChanged(control: UISwitch) {
prefs.setBool(control.on, forKey: prefKey)
settingDidChange?(control.on)
}
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional settingIsValid and settingDidChange callback
/// If settingIsValid returns false, the Setting will not change and the text remains red.
class StringSetting: Setting, UITextFieldDelegate {
let prefKey: String
private let Padding: CGFloat = 8
private let prefs: Prefs
private let defaultValue: String?
private let placeholder: String
private let settingDidChange: (String? -> Void)?
private let settingIsValid: (String? -> Bool)?
let textField = UITextField()
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: (String? -> Bool)? = nil, settingDidChange: (String? -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
super.init()
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
textField.placeholder = placeholder
textField.textAlignment = .Center
textField.delegate = self
textField.addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged)
cell.userInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
textField.snp_makeConstraints { make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
}
textField.text = prefs.stringForKey(prefKey) ?? defaultValue
textFieldDidChange(textField)
}
override func onClick(navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
private func isValid(value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
/// This gives subclasses an opportunity to treat the user input string
/// before it is saved or tested.
/// Default implementation does nothing.
func prepareValidValue(userInput value: String?) -> String? {
return value
}
@objc func textFieldDidChange(textField: UITextField) {
let color = isValid(textField.text) ? UIConstants.TableViewRowTextColor : UIConstants.DestructiveRed
textField.textColor = color
}
@objc func textFieldShouldReturn(textField: UITextField) -> Bool {
return isValid(textField.text)
}
@objc func textFieldDidEndEditing(textField: UITextField) {
let text = textField.text
if !isValid(text) {
return
}
if let text = prepareValidValue(userInput: text) {
prefs.setString(text, forKey: prefKey)
} else {
prefs.removeObjectForKey(prefKey)
}
// Call settingDidChange with text or nil.
settingDidChange?(text)
}
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional isEnabled and mandatory onClick callback
/// isEnabled is called on each tableview.reloadData. If it returns
/// false then the 'button' appears disabled.
class ButtonSetting: Setting {
let onButtonClick: (UINavigationController?) -> ()
let destructive: Bool
let isEnabled: (() -> Bool)?
init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: UINavigationController? -> ()) {
self.onButtonClick = onClick
self.destructive = destructive
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if isEnabled?() ?? true {
cell.textLabel?.textColor = destructive ? UIConstants.DestructiveRed : UIConstants.HighlightBlue
} else {
cell.textLabel?.textColor = UIConstants.TableViewDisabledRowTextColor
}
cell.textLabel?.textAlignment = NSTextAlignment.Center
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.selectionStyle = .None
}
override func onClick(navigationController: UINavigationController?) {
if isEnabled?() ?? true {
onButtonClick(navigationController)
}
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .None
}
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
@objc
protocol SettingsDelegate: class {
func settingsOpenURLInNewTab(url: NSURL)
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection]
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var settings = [SettingSection]()
weak var settingsDelegate: SettingsDelegate?
var profile: Profile!
var tabManager: TabManager!
/// Used to calculate cell heights.
private lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = UISwitch()
return cell
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
tableView.estimatedRowHeight = 44
tableView.estimatedSectionHeaderHeight = 44
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
settings = generateSettings()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidStartSyncing, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidFinishSyncing, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SettingsTableViewController.SELfirefoxAccountDidChange), name: NotificationFirefoxAccountChanged, object: nil)
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidStartSyncing, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
// Override to provide settings in subclasses
func generateSettings() -> [SettingSection] {
return []
}
@objc private func SELsyncDidChangeState() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { state in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
@objc func SELfirefoxAccountDidChange() {
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = UITableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
return headerView
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let section = settings[indexPath.section]
// Workaround for calculating the height of default UITableViewCell cells with a subtitle under
// the title text label.
if let setting = section[indexPath.row] where setting is BoolSetting && setting.status != nil {
return calculateStatusCellHeightForSetting(setting)
}
return UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] where setting.enabled {
setting.onClick(navigationController)
}
}
private func calculateStatusCellHeightForSetting(setting: Setting) -> CGFloat {
dummyToggleCell.layoutSubviews()
let topBottomMargin: CGFloat = 10
let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left
return
heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) +
heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) +
2 * topBottomMargin
}
private func heightForLabel(label: UILabel, width: CGFloat, text: String?) -> CGFloat {
guard let text = text else { return 0 }
let size = CGSize(width: width, height: CGFloat.max)
let attrs = [NSFontAttributeName: label.font]
let boundingRect = NSString(string: text).boundingRectWithSize(size,
options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
}
class SettingsTableFooterView: UIView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
image.accessibilityIdentifier = "SettingsTableFooterView.logo"
return image
}()
private lazy var topBorder: CALayer = {
let topBorder = CALayer()
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
return topBorder
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIConstants.TableViewHeaderBackgroundColor
layer.addSublayer(topBorder)
addSubview(logo)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5)
logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
}
}
struct SettingsTableSectionHeaderFooterViewUX {
static let titleHorizontalPadding: CGFloat = 15
static let titleVerticalPadding: CGFloat = 6
static let titleVerticalLongPadding: CGFloat = 20
}
class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView {
enum TitleAlignment {
case Top
case Bottom
}
var titleAlignment: TitleAlignment = .Bottom {
didSet {
remakeTitleAlignmentConstraints()
}
}
var showTopBorder: Bool = true {
didSet {
topBorder.hidden = !showTopBorder
}
}
var showBottomBorder: Bool = true {
didSet {
bottomBorder.hidden = !showBottomBorder
}
}
lazy var titleLabel: UILabel = {
var headerLabel = UILabel()
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
headerLabel.numberOfLines = 0
return headerLabel
}()
private lazy var topBorder: UIView = {
let topBorder = UIView()
topBorder.backgroundColor = UIConstants.SeparatorColor
return topBorder
}()
private lazy var bottomBorder: UIView = {
let bottomBorder = UIView()
bottomBorder.backgroundColor = UIConstants.SeparatorColor
return bottomBorder
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
addSubview(topBorder)
addSubview(bottomBorder)
setupInitialConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupInitialConstraints() {
bottomBorder.snp_makeConstraints { make in
make.bottom.left.right.equalTo(self)
make.height.equalTo(0.5)
}
topBorder.snp_makeConstraints { make in
make.top.left.right.equalTo(self)
make.height.equalTo(0.5)
}
remakeTitleAlignmentConstraints()
}
override func prepareForReuse() {
super.prepareForReuse()
showTopBorder = true
showBottomBorder = true
titleLabel.text = nil
titleAlignment = .Bottom
}
private func remakeTitleAlignmentConstraints() {
switch titleAlignment {
case .Top:
titleLabel.snp_remakeConstraints { make in
make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding)
make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding)
make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding)
}
case .Bottom:
titleLabel.snp_remakeConstraints { make in
make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding)
make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding)
make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding)
}
}
}
}
|
fd37728ae581f7b03a7c7d39056a0ef9
| 37.446043 | 304 | 0.682448 | false | false | false | false |
CM-Studio/NotLonely-iOS
|
refs/heads/master
|
NotLonely-iOS/ViewController/Login/RegisterViewController.swift
|
mit
|
1
|
//
// RegisterViewController.swift
// NotLonely-iOS
//
// Created by plusub on 4/27/16.
// Copyright © 2016 cm. All rights reserved.
//
import UIKit
protocol RegisterDelegate {
func updateTextField()
}
class RegisterViewController: BaseViewController {
var delegate: RegisterDelegate?
@IBOutlet weak var usernameTextField: InputTextField! {
didSet {
usernameTextField.setPlaceHolderTextColor("用户名")
usernameTextField.setLeftImage("ic_user")
usernameTextField.setlineColor(UIColor.whiteColor())
}
}
@IBOutlet weak var passwordTextField: InputTextField! {
didSet {
passwordTextField.setPlaceHolderTextColor("密码")
passwordTextField.setLeftImage("ic_passwd")
passwordTextField.setlineColor(UIColor.whiteColor())
}
}
@IBOutlet weak var repasswordTextField: InputTextField! {
didSet {
repasswordTextField.setPlaceHolderTextColor("密码")
repasswordTextField.setLeftImage("ic_passwd")
repasswordTextField.setlineColor(UIColor.whiteColor())
}
}
@IBOutlet weak var registerButton: UIButton! {
didSet {
let gradient = vertical_gradientLayer()
gradient.frame = self.registerButton.bounds
registerButton.layer.insertSublayer(gradient, atIndex: 0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar.shadowImage = UIImage.init()
self.navigationController?.navigationBar.setBackgroundImage(UIImage.init(), forBarMetrics: .Default)
let viewModel = RegisterViewModel(
input: (
usertextview: usernameTextField.rx_text.asObservable(),
pwdtextview: passwordTextField.rx_text.asObservable(),
repwdtextview: repasswordTextField.rx_text.asObservable(),
buttonTaps: registerButton.rx_tap.asObservable()
),
dependency: (
validation: NLValidationService.sharedValidation,
API: VMNetWorkApi.sharedVMNetWorkApi
)
)
viewModel.buttonEnable.subscribeNext{ [weak self] valid in
self?.registerButton.enabled = valid
self?.registerButton.alpha = valid ? 1.0 : 0.5
}
.addDisposableTo(disposeBag)
viewModel.model.subscribeNext { valid in
self.showHudTipStr(valid.msg)
self.delegate?.updateTextField()
self.dismissViewControllerAnimated(true, completion: nil)
}
.addDisposableTo(disposeBag)
}
@IBAction func backToLogin(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
04a12717f7fe18f3d62b35894749da27
| 30.391304 | 108 | 0.620845 | false | false | false | false |
AlanAherne/BabyTunes
|
refs/heads/master
|
BabyTunes/Pods/RealmSwift/RealmSwift/List.swift
|
gpl-3.0
|
3
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/// :nodoc:
/// Internal class. Do not use directly.
public class ListBase: RLMListBase {
// Printable requires a description property defined in Swift (and not obj-c),
// and it has to be defined as override, which can't be done in a
// generic class.
/// Returns a human-readable description of the objects contained in the List.
@objc public override var description: String {
return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
}
@objc private func descriptionWithMaxDepth(_ depth: UInt) -> String {
return RLMDescriptionWithMaxDepth("List", _rlmArray, depth)
}
/// Returns the number of objects in this List.
public var count: Int { return Int(_rlmArray.count) }
}
/**
`List` is the container type in Realm used to define to-many relationships.
Like Swift's `Array`, `List` is a generic type that is parameterized on the type of `Object` it stores.
Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them
is opened as read-only.
Lists can be filtered and sorted with the same predicates as `Results<Element>`.
Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`.
*/
public final class List<Element: RealmCollectionValue>: ListBase {
// MARK: Properties
/// The Realm which manages the list, or `nil` if the list is unmanaged.
public var realm: Realm? {
return _rlmArray.realm.map { Realm($0) }
}
/// Indicates if the list can no longer be accessed.
public var isInvalidated: Bool { return _rlmArray.isInvalidated }
// MARK: Initializers
/// Creates a `List` that holds Realm model objects of type `Element`.
public override init() {
super.init(array: Element._rlmArray())
}
internal init(rlmArray: RLMArray<AnyObject>) {
super.init(array: rlmArray)
}
// MARK: Index Retrieval
/**
Returns the index of an object in the list, or `nil` if the object is not present.
- parameter object: An object to find.
*/
public func index(of object: Element) -> Int? {
return notFoundToNil(index: _rlmArray.index(of: dynamicBridgeCast(fromSwift: object) as AnyObject))
}
/**
Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? {
return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate))
}
/**
Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
}
// MARK: Object Retrieval
/**
Returns the object at the given index (get), or replaces the object at the given index (set).
- warning: You can only set an object during a write transaction.
- parameter index: The index of the object to retrieve or replace.
*/
public subscript(position: Int) -> Element {
get {
throwForNegativeIndex(position)
return dynamicBridgeCast(fromObjectiveC: _rlmArray.object(at: UInt(position)))
}
set {
throwForNegativeIndex(position)
_rlmArray.replaceObject(at: UInt(position), with: dynamicBridgeCast(fromSwift: newValue) as AnyObject)
}
}
/// Returns the first object in the list, or `nil` if the list is empty.
public var first: Element? { return _rlmArray.firstObject().map(dynamicBridgeCast) }
/// Returns the last object in the list, or `nil` if the list is empty.
public var last: Element? { return _rlmArray.lastObject().map(dynamicBridgeCast) }
// MARK: KVC
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's
objects.
*/
@nonobjc public func value(forKey key: String) -> [AnyObject] {
return _rlmArray.value(forKeyPath: key)! as! [AnyObject]
}
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
@nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] {
return _rlmArray.value(forKeyPath: keyPath) as! [AnyObject]
}
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
public override func setValue(_ value: Any?, forKey key: String) {
return _rlmArray.setValue(value, forKeyPath: key)
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the list.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
return Results<Element>(_rlmArray.objects(with: NSPredicate(format: predicateFormat,
argumentArray: unwrapOptionals(in: args))))
}
/**
Returns a `Results` containing all objects matching the given predicate in the list.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> {
return Results<Element>(_rlmArray.objects(with: predicate))
}
// MARK: Sorting
/**
Returns a `Results` containing the objects in the list, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
}
/**
Returns a `Results` containing the objects in the list, but sorted.
- warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return Results<Element>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is
empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<T: MinMaxType>(ofProperty property: String) -> T? {
return _rlmArray.min(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list
is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose maximum value is desired.
*/
public func max<T: MinMaxType>(ofProperty property: String) -> T? {
return _rlmArray.max(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the sum of the values of a given property over all the objects in the list.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<T: AddableType>(ofProperty property: String) -> T {
return dynamicBridgeCast(fromObjectiveC: _rlmArray.sum(ofProperty: property))
}
/**
Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average(ofProperty property: String) -> Double? {
return _rlmArray.average(ofProperty: property).map(dynamicBridgeCast)
}
// MARK: Mutation
/**
Appends the given object to the end of the list.
If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing
the receiver.
- warning: This method may only be called during a write transaction.
- parameter object: An object.
*/
public func append(_ object: Element) {
_rlmArray.add(dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Appends the objects in the given sequence to the end of the list.
- warning: This method may only be called during a write transaction.
*/
public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element {
for obj in objects {
_rlmArray.add(dynamicBridgeCast(fromSwift: obj) as AnyObject)
}
}
/**
Inserts an object at the given index.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter object: An object.
- parameter index: The index at which to insert the object.
*/
public func insert(_ object: Element, at index: Int) {
throwForNegativeIndex(index)
_rlmArray.insert(dynamicBridgeCast(fromSwift: object) as AnyObject, at: UInt(index))
}
/**
Removes an object at the given index. The object is not removed from the Realm that manages it.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter index: The index at which to remove the object.
*/
public func remove(at index: Int) {
throwForNegativeIndex(index)
_rlmArray.removeObject(at: UInt(index))
}
/**
Removes all objects from the list. The objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeAll() {
_rlmArray.removeAllObjects()
}
/**
Replaces an object at the given index with a new object.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter index: The index of the object to be replaced.
- parameter object: An object.
*/
public func replace(index: Int, object: Element) {
throwForNegativeIndex(index)
_rlmArray.replaceObject(at: UInt(index), with: dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Moves the object at the given source index to the given destination index.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with invalid indices.
- parameter from: The index of the object to be moved.
- parameter to: index to which the object at `from` should be moved.
*/
public func move(from: Int, to: Int) {
throwForNegativeIndex(from)
throwForNegativeIndex(to)
_rlmArray.moveObject(at: UInt(from), to: UInt(to))
}
/**
Exchanges the objects in the list at given indices.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with invalid indices.
- parameter index1: The index of the object which should replace the object at index `index2`.
- parameter index2: The index of the object which should replace the object at index `index1`.
*/
public func swapAt(_ index1: Int, _ index2: Int) {
throwForNegativeIndex(index1, parameterName: "index1")
throwForNegativeIndex(index2, parameterName: "index2")
_rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2))
}
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken {
return _rlmArray.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
}
}
}
extension List where Element: MinMaxType {
/**
Returns the minimum (lowest) value in the list, or `nil` if the list is empty.
*/
public func min() -> Element? {
return _rlmArray.min(ofProperty: "self").map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value in the list, or `nil` if the list is empty.
*/
public func max() -> Element? {
return _rlmArray.max(ofProperty: "self").map(dynamicBridgeCast)
}
}
extension List where Element: AddableType {
/**
Returns the sum of the values in the list.
*/
public func sum() -> Element {
return sum(ofProperty: "self")
}
/**
Returns the average of the values in the list, or `nil` if the list is empty.
*/
public func average() -> Double? {
return average(ofProperty: "self")
}
}
extension List: RealmCollection {
/// The type of the objects stored within the list.
public typealias ElementType = Element
// MARK: Sequence Support
/// Returns a `RLMIterator` that yields successive elements in the `List`.
public func makeIterator() -> RLMIterator<Element> {
return RLMIterator(collection: _rlmArray)
}
/**
Replace the given `subRange` of elements with `newElements`.
- parameter subrange: The range of elements to be replaced.
- parameter newElements: The new elements to be inserted into the List.
*/
public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C)
where C.Iterator.Element == Element {
for _ in subrange.lowerBound..<subrange.upperBound {
remove(at: subrange.lowerBound)
}
for x in newElements.reversed() {
insert(x, at: subrange.lowerBound)
}
}
// This should be inferred, but Xcode 8.1 is unable to
/// :nodoc:
public typealias Indices = DefaultRandomAccessIndices<List>
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// :nodoc:
public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken {
let anyCollection = AnyRealmCollection(self)
return _rlmArray.addNotificationBlock { _, change, error in
block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
}
}
}
#if swift(>=4.0)
// MARK: - MutableCollection conformance, range replaceable collection emulation
extension List: MutableCollection {
#if swift(>=4.1)
public typealias SubSequence = Slice<List>
#else
public typealias SubSequence = RandomAccessSlice<List>
#endif
/**
Returns the objects at the given range (get), or replaces the objects at the
given range with new objects (set).
- warning: Objects may only be set during a write transaction.
- parameter index: The index of the object to retrieve or replace.
*/
public subscript(bounds: Range<Int>) -> SubSequence {
get {
return SubSequence(base: self, bounds: bounds)
}
set {
replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue)
}
}
/**
Removes the specified number of objects from the beginning of the list. The
objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeFirst(_ number: Int = 1) {
let count = Int(_rlmArray.count)
guard number <= count else {
throwRealmException("It is not possible to remove more objects (\(number)) from a list"
+ " than it already contains (\(count)).")
return
}
for _ in 0..<number {
_rlmArray.removeObject(at: 0)
}
}
/**
Removes the specified number of objects from the end of the list. The objects
are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeLast(_ number: Int = 1) {
let count = Int(_rlmArray.count)
guard number <= count else {
throwRealmException("It is not possible to remove more objects (\(number)) from a list"
+ " than it already contains (\(count)).")
return
}
for _ in 0..<number {
_rlmArray.removeLastObject()
}
}
/**
Inserts the items in the given collection into the list at the given position.
- warning: This method may only be called during a write transaction.
*/
public func insert<C: Collection>(contentsOf newElements: C, at i: Int) where C.Iterator.Element == Element {
var currentIndex = i
for item in newElements {
insert(item, at: currentIndex)
currentIndex += 1
}
}
/**
Removes objects from the list at the given range.
- warning: This method may only be called during a write transaction.
*/
public func removeSubrange(_ bounds: Range<Int>) {
removeSubrange(bounds.lowerBound..<bounds.upperBound)
}
/// :nodoc:
public func removeSubrange(_ bounds: ClosedRange<Int>) {
removeSubrange(bounds.lowerBound...bounds.upperBound)
}
//// :nodoc:
public func removeSubrange(_ bounds: CountableRange<Int>) {
for _ in bounds {
remove(at: bounds.lowerBound)
}
}
/// :nodoc:
public func removeSubrange(_ bounds: CountableClosedRange<Int>) {
for _ in bounds {
remove(at: bounds.lowerBound)
}
}
/// :nodoc:
public func removeSubrange(_ bounds: DefaultRandomAccessIndices<List>) {
removeSubrange(bounds.startIndex..<bounds.endIndex)
}
/// :nodoc:
public func replaceSubrange<C: Collection>(_ subrange: ClosedRange<Int>, with newElements: C)
where C.Iterator.Element == Element {
removeSubrange(subrange)
insert(contentsOf: newElements, at: subrange.lowerBound)
}
/// :nodoc:
public func replaceSubrange<C: Collection>(_ subrange: CountableRange<Int>, with newElements: C)
where C.Iterator.Element == Element {
removeSubrange(subrange)
insert(contentsOf: newElements, at: subrange.lowerBound)
}
/// :nodoc:
public func replaceSubrange<C: Collection>(_ subrange: CountableClosedRange<Int>, with newElements: C)
where C.Iterator.Element == Element {
removeSubrange(subrange)
insert(contentsOf: newElements, at: subrange.lowerBound)
}
/// :nodoc:
public func replaceSubrange<C: Collection>(_ subrange: DefaultRandomAccessIndices<List>, with newElements: C)
where C.Iterator.Element == Element {
removeSubrange(subrange)
insert(contentsOf: newElements, at: subrange.startIndex)
}
}
#else
// MARK: - RangeReplaceableCollection support
extension List: RangeReplaceableCollection {
/**
Removes the last object in the list. The object is not removed from the Realm that manages it.
- warning: This method may only be called during a write transaction.
*/
public func removeLast() {
guard _rlmArray.count > 0 else {
throwRealmException("It is not possible to remove an object from an empty list.")
return
}
_rlmArray.removeLastObject()
}
#if swift(>=3.2)
// The issue described below is fixed in Swift 3.2 and above.
#elseif swift(>=3.1)
// These should not be necessary, but Swift 3.1's compiler fails to infer the `SubSequence`,
// and the standard library neglects to provide the default implementation of `subscript`
/// :nodoc:
public typealias SubSequence = RangeReplaceableRandomAccessSlice<List>
/// :nodoc:
public subscript(slice: Range<Int>) -> SubSequence {
return SubSequence(base: self, bounds: slice)
}
#endif
}
#endif
// MARK: - AssistedObjectiveCBridgeable
extension List: AssistedObjectiveCBridgeable {
internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List {
guard let objectiveCValue = objectiveCValue as? RLMArray<AnyObject> else { preconditionFailure() }
return List(rlmArray: objectiveCValue)
}
internal var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: _rlmArray, metadata: nil)
}
}
// MARK: - Unavailable
extension List {
@available(*, unavailable, renamed: "remove(at:)")
public func remove(objectAtIndex: Int) { fatalError() }
}
|
41391f72ca45c283aa290b73202938ee
| 36.029577 | 128 | 0.662242 | false | false | false | false |
Ramotion/showroom
|
refs/heads/master
|
Showroom/DribbbleShots/DribbbleShotsTransition.swift
|
gpl-3.0
|
1
|
//
// DribbbleShotsTransition.swift
// Showroom
//
// Created by Dmitry Nesterenko on 02/07/2018.
// Copyright © 2018 Alex K. All rights reserved.
//
import UIKit
protocol DribbbleShotsTransitionSource {
func dribbbleShotsTransitionSourceView() -> UIView
}
protocol DribbbleShotsTransitionDestination {
}
final class DribbbleShotsTransition : NSObject, UIViewControllerAnimatedTransitioning {
enum Direction {
case dismissing(destinationView: UIView)
case presenting(sourceView: UIView)
}
private let direction: Direction
init(direction: Direction) {
self.direction = direction
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.23
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch direction {
case .presenting(let sourceView):
animatePresentation(from: sourceView, using: transitionContext)
case .dismissing(let destinationView):
animateDismissal(to: destinationView, using: transitionContext)
}
}
private func animatePresentation(from sourceView: UIView, using transitionContext: UIViewControllerContextTransitioning) {
guard
let toViewController = transitionContext.viewController(forKey: .to),
let toView = transitionContext.view(forKey: .to) else {
transitionContext.completeTransition(false)
return
}
let containerView = transitionContext.containerView
let toViewFinalFrame = transitionContext.finalFrame(for: toViewController)
let duration = transitionDuration(using: transitionContext)
toView.alpha = 0
toView.frame = toViewFinalFrame
containerView.addSubview(toView)
let maskViewInitialFrame = sourceView.convert(sourceView.bounds, to: containerView)
let maskView = UIView(frame: maskViewInitialFrame)
maskView.backgroundColor = .black
toView.mask = maskView
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseOut], animations: {
toView.alpha = 1
maskView.frame = toView.bounds
}, completion: { finished in
let didComplete = !transitionContext.transitionWasCancelled
if !didComplete {
toView.removeFromSuperview()
} else {
toView.mask = nil
}
transitionContext.completeTransition(didComplete)
})
}
private func animateDismissal(to destinationView: UIView, using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromView = transitionContext.view(forKey: .from) else {
transitionContext.completeTransition(false)
return
}
let containerView = transitionContext.containerView
let duration = transitionDuration(using: transitionContext)
let maskViewFinalFrame = destinationView.convert(destinationView.bounds, to: containerView)
let maskView = UIView(frame: fromView.bounds)
maskView.backgroundColor = .black
fromView.mask = maskView
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseIn], animations: {
fromView.alpha = 0
maskView.frame = maskViewFinalFrame
}, completion: { finished in
let didComplete = !transitionContext.transitionWasCancelled
if didComplete {
fromView.removeFromSuperview()
} else {
fromView.mask = nil
}
transitionContext.completeTransition(didComplete)
})
}
}
|
a253728ddd9c4821e7f4d24223b8786f
| 34.743119 | 126 | 0.648871 | false | false | false | false |
gorozco58/Apps-List
|
refs/heads/master
|
Apps List/Application/Networking/CategoryAPI.swift
|
mit
|
1
|
//
// CategoryAPI.swift
// Apps List
//
// Created by Giovanny Orozco on 3/30/16.
// Copyright © 2016 Giovanny Orozco. All rights reserved.
//
import Alamofire
typealias ApiError = Error<ApiErrorCode>
struct Error<ErrorCode>: ErrorType {
let title: String?
let message: String?
let code: ErrorCode?
}
extension Error {
static func defaultError() -> ApiError {
return ApiError(title: "Que ", message: "fuck", code: .ApiErrorUnknown)
}
static func apiError(error error: NSError, data: NSData?) -> ApiError {
let apiErrorCode = ApiErrorCode(rawValue: error.code) ?? .ApiErrorUnknown
let error = ApiError(title: "", message: error.localizedDescription, code: apiErrorCode)
return error
}
}
enum ApiErrorCode: Int {
case ApiErrorUnknown = 0
case ApiErrorCodeOne = 1
case ApiErrorCodeTwo = 2
}
struct CategoryAPI {
func getCategoriesList(completion:(result:(Result<[Category], ApiError>)) -> Void) {
Alamofire.request(AlamofireRouter.Categories).validate().responseJSON { response in
var result: Result<[Category], ApiError> = Result.Failure(ApiError.defaultError())
switch response.result {
case .Success(let value):
if let feed = value["feed"] as? [String : AnyObject] {
if let entries = feed["entry"] as? [[String : AnyObject]] {
let categories = CategoryFactory().makeCategories(entries)
result = Result.Success(categories)
}
}
case .Failure(let error):
let error = ApiError.apiError(error: error, data: response.data)
result = Result.Failure(error)
}
completion(result: result)
}
}
}
enum ImageAsset: String {
case Logo = "logo.png"
var image: UIImage? {
return UIImage(named: self.rawValue)
}
}
struct CategoryFactory {
private struct CategoryKey {
static let Category = "category"
}
func makeCategories(jsonArray:[[String: AnyObject]]) -> [Category] {
var categories = [Category]()
for appDictionary in jsonArray {
if let categoryDictionary = appDictionary[CategoryKey.Category] as? [String : AnyObject],
let categoryAttributes = categoryDictionary[InternalParameterKey.Attributes.rawValue] as? [String : AnyObject],
var category = try? Category(jsonDictionary: categoryAttributes) {
let app = try? App(jsonDictionary: appDictionary)
if categories.contains(category) {
if let app = app {
category = categories[categories.indexOf(category)!]
category.applications += [app]
}
} else {
if let app = app {
category.applications += [app]
}
categories += [category]
}
}
}
return categories
}
}
|
87c7f84217808ac60a42de077c02df9b
| 27.991379 | 127 | 0.533155 | false | false | false | false |
BellAppLab/MultiPicker
|
refs/heads/master
|
Source/MultiPicker.swift
|
mit
|
1
|
import UIKit
import Photos
//MARK: Delegate
/**
MultiPickerable
An object that can handle a MultiPicker.
- discussion This is how you get your pictures. :)
*/
@objc public protocol MultiPickerable: NSObjectProtocol
{
/**
Did finish
- param multiPicker The MultiPicker instance calling its delegate
- discussion The MultiPicker only calls this method when its Cancel and Done buttons are visible (i.e. when it's being presented modally). You can access the selected assets by calling `multiPicker.picked`.
*/
func didFinish(multiPicker: MultiPicker)
optional func multi(picker: MultiPicker, shouldSelectAsset asset: PHAsset, atIndex index: Int) -> Bool
optional func multi(picker: MultiPicker, didSelect asset: PHAsset, atIndex index: Int)
optional func multi(picker: MultiPicker, shouldDeselectAsset asset: PHAsset, atIndex index: Int) -> Bool
optional func multi(picker: MultiPicker, didDeselect asset: PHAsset, atIndex index: Int)
optional func didClear(multiPicker: MultiPicker)
}
//MARK: - Main
/**
Multi Picker
This is how you display the pictures. :)
*/
public class MultiPicker: UINavigationController
{
//MARK: Validation
public enum Error: ErrorType, CustomDebugStringConvertible
{
case minimumItemsTooLow
case minimumItemsTooHigh
case maximumItemsTooLow
public var debugDescription: String {
#if DEBUG
switch self
{
case .MinimumItemsTooLow: return "MinimumItemsTooLow: Are you sure you haven't set the minimum items to a value below 1? Does it make sense to have a minimum below 1?"
case .MinimumItemsTooHigh: return "MinimumItemsTooHigh: Are you sure you haven't set the minimum items to a value that's higher than 1 and ALSO set the 'multiple' property to false..."
case .MaximumItemsTooLow: return "MaximumItemsTooLow: Are you sure you haven't set the maximum items to a value that's higher than the minumum?"
}
#else
return ""
#endif
}
}
//MARK: Delegate
/**
Delegate
Set the delegate to get the pictures the user selects.
*/
@IBOutlet public weak var able: MultiPickerable?
//MARK: Setup
/**
Make with delegate
- param multiPickerable A delegate
- discussion If you init the MultiPicker this way, we assume you're creating it programmatically and therefore you need the UI to be created for you.
*/
public class func make(multiPickerable: MultiPickerable) -> MultiPicker?
{
var bundle = NSBundle(forClass: MultiPicker.self)
if let path = bundle.pathForResource("MultiPicker", ofType: "bundle") {
bundle = NSBundle(path: path)!
}
if let picker = UIStoryboard(name: "MultiPicker", bundle: bundle).instantiateInitialViewController() as? MultiPicker {
picker.able = multiPickerable
return picker
}
return nil
}
override public func viewDidLoad() {
super.viewDidLoad()
if let controller = self.topViewController as? AlbumList {
controller.multiPicker = self
}
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
try! self.validate()
}
/**
Multiple
Toggles the ability to select multiple assets.
- discussion It doesn't really make much sense to turn this off, since the Library is called MultiPicker, but still... Defaults to true.
*/
@IBInspectable public var multiple: Bool = true
/**
Minimum items
Sets the minimum number of items that need to be selected for the Cancel and Done buttons to be enabled and for the count toolbar to be visible. This value must not be lower than 1. Defaults to 1.
*/
@IBInspectable public var minimumItems: Int = 1
/**
Maximum items
Sets the maximum number of items that can be selected. Defaults to 100.
*/
@IBInspectable public var maximumItems: Int = 100
/**
Shows count
Toggles the ability to show the number of selected items (on a toolbar). Defaults to true.
*/
@IBInspectable public var showsCount: Bool = true
/**
Prompt
The navigationItem.prompt to be used.
*/
@IBInspectable public var prompt: String? = nil
/**
Cell spacing
The minimum space between grid cells.
*/
@IBInspectable public var cellSpacing: CGFloat = 10
//MARK: Assets
/**
Subtypes
The Asset Collection Subtypes that should be used to fetch assets.
*/
public var subtypes: [PHAssetCollectionSubtype] = [.SmartAlbumUserLibrary, .AlbumMyPhotoStream, .SmartAlbumPanoramas, .SmartAlbumVideos, .SmartAlbumBursts]
/**
Selected
The currently selected assets.
*/
public var picked: [PHAsset] = []
//MARK: Private
private func validate() throws {
if self.minimumItems < 1 {
throw Error.MinimumItemsTooLow
}
if !self.multiple {
if self.minimumItems > 1 {
throw Error.MinimumItemsTooHigh
} else {
self.maximumItems = self.minimumItems
}
}
if self.maximumItems < self.minimumItems {
throw Error.MaximumItemsTooLow
}
if self.cellSpacing < 0 {
self.cellSpacing = 0
}
}
func shouldAdd(asset: PHAsset) -> Bool {
return self.picked.count < self.maximumItems && self.able?.multi?(self, shouldSelectAsset: asset, atIndex: self.picked.count) ?? true
}
func add(asset: PHAsset) {
self.picked.append(asset)
self.able?.multi?(self, didSelect: asset, atIndex: self.picked.count - 1)
}
func clear() {
self.picked = []
}
func shouldRemove(asset: PHAsset) -> Bool {
if let index = self.picked.indexOf(asset) {
return self.able?.multi?(self, shouldDeselectAsset: asset, atIndex: index) ?? true
}
return false
}
func remove(asset: PHAsset) {
if let index = self.picked.indexOf(asset) {
self.picked.removeAtIndex(index)
self.able?.multi?(self, didDeselect: asset, atIndex: index)
}
}
var doneButtonVisible: Bool {
return self.cancelButtonVisible
}
var cancelButtonVisible: Bool {
return self.presentingViewController != nil || self.popoverPresentationController != nil
}
var doneButtonEnabled: Bool {
return self.doneButtonVisible && self.picked.count >= self.minimumItems
}
var clearButtonVisible: Bool {
return !self.doneButtonVisible && self.picked.count > 0
}
//Actions
func donePressed(sender: UIBarButtonItem) {
self.able?.didFinish(self)
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func cancelPressed(sender: UIBarButtonItem) {
self.clear()
self.able?.didFinish(self)
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func clearPressed(sender: UIBarButtonItem) {
self.clear()
self.able?.didClear?(self)
}
}
//MARK: - Children
internal protocol MultiPickerChild {
weak var multiPicker: MultiPicker! { get set }
func updateUI()
}
//MARK: - Aux
private func -=(lhs: inout [Int: PHAsset], rhs: inout Int)
{
lhs.removeValueForKey(rhs)
while let item = lhs[rhs + 1] {
lhs.updateValue(item, forKey: rhs)
rhs += 1
}
lhs.removeValueForKey(rhs)
}
internal extension Array
{
func find(block: (Generator.Element) -> Bool) -> Generator.Element?
{
for e in self {
if block(e) {
return e
}
}
return nil
}
}
|
a13354f153b0d4b2e09d6f7a8d7d7b19
| 28.516245 | 213 | 0.621331 | false | false | false | false |
p4checo/APNSubGroupOperationQueue
|
refs/heads/master
|
Tests/DynamicSubGroupOperationQueueTests.swift
|
mit
|
1
|
//
// DynamicSubGroupOperationQueueTests.swift
// APNSubGroupOperationQueue
//
// Created by André Pacheco Neves on 12/02/2017.
// Copyright © 2017 André Pacheco Neves. All rights reserved.
//
import XCTest
@testable import APNSubGroupOperationQueue
class DynamicSubGroupOperationQueueTests: XCTestCase {
var subGroupQueue: DynamicSubGroupOperationQueue!
override func setUp() {
super.setUp()
subGroupQueue = DynamicSubGroupOperationQueue()
subGroupQueue.maxConcurrentOperationCount = OperationQueue.defaultMaxConcurrentOperationCount
}
override func tearDown() {
subGroupQueue = nil
super.tearDown()
}
// MARK: - addOperation
func testAddOperation_withSingleGroup_mustExecuteSerially() {
let (key, value, result) = ("key", "123456", Box<String>(""))
let ops = stringAppendingBlockOperations(for: splitString(value), sharedBox: result)
subGroupQueue.isSuspended = true
ops.forEach { subGroupQueue.addOperation($0, withKey: key) }
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[key].count == 0)
XCTAssert(result.value == value, "\(result.value) didn't match expected value \(value)")
}
func testAddOperation_withMutipleGroups_mustExecuteEachGroupSerially() {
let (keyA, valueA, resultA) = ("A", "123456", Box<String>(""))
let (keyB, valueB, resultB) = (1337, "abcdef", Box<String>(""))
let (keyC, valueC, resultC) = (Date(), "ABCDEF", Box<String>(""))
let opsA = stringAppendingBlockOperations(for: splitString(valueA), sharedBox: resultA)
let opsB = stringAppendingBlockOperations(for: splitString(valueB), sharedBox: resultB)
let opsC = stringAppendingBlockOperations(for: splitString(valueC), sharedBox: resultC)
subGroupQueue.isSuspended = true
// schedule them in order *inside* each subgroup, but *shuffled* between subgroups
subGroupQueue.addOperation(opsA[0], withKey: keyA)
subGroupQueue.addOperation(opsB[0], withKey: keyB)
subGroupQueue.addOperation(opsC[0], withKey: keyC)
subGroupQueue.addOperation(opsA[1], withKey: keyA)
subGroupQueue.addOperation(opsB[1], withKey: keyB)
subGroupQueue.addOperation(opsB[2], withKey: keyB)
subGroupQueue.addOperation(opsA[2], withKey: keyA)
subGroupQueue.addOperation(opsC[1], withKey: keyC)
subGroupQueue.addOperation(opsC[2], withKey: keyC)
subGroupQueue.addOperation(opsA[3], withKey: keyA)
subGroupQueue.addOperation(opsB[3], withKey: keyB)
subGroupQueue.addOperation(opsA[4], withKey: keyA)
subGroupQueue.addOperation(opsC[3], withKey: keyC)
subGroupQueue.addOperation(opsB[4], withKey: keyB)
subGroupQueue.addOperation(opsC[4], withKey: keyC)
subGroupQueue.addOperation(opsA[5], withKey: keyA)
subGroupQueue.addOperation(opsB[5], withKey: keyB)
subGroupQueue.addOperation(opsC[5], withKey: keyC)
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[keyA].count == 0)
XCTAssert(subGroupQueue[keyB].count == 0)
XCTAssert(subGroupQueue[keyC].count == 0)
XCTAssert(resultA.value == valueA, "\(resultA.value) didn't match expected value \(valueA)")
XCTAssert(resultB.value == valueB, "\(resultB.value) didn't match expected value \(valueB)")
XCTAssert(resultC.value == valueC, "\(resultC.value) didn't match expected value \(valueC)")
}
// MARK: - addOperations
func testAddOperations_withSingleGroup_mustExecuteSerially() {
let (key, value, result) = ("key", "123456", Box<String>(""))
let ops = stringAppendingBlockOperations(for: splitString(value), sharedBox: result)
subGroupQueue.addOperations(ops, withKey: key, waitUntilFinished: true)
XCTAssert(subGroupQueue[key].count == 0)
XCTAssert(result.value == value, "\(result) didn't match expected value \(value)")
}
func testAddOperations_withMutipleGroups_mustExecuteEachGroupSerially() {
let (keyA, valueA, resultA) = ("A", "123456", Box<String>(""))
let (keyB, valueB, resultB) = (1337, "abcdef", Box<String>(""))
let (keyC, valueC, resultC) = (Date(), "ABCDEF", Box<String>(""))
let opsA = stringAppendingBlockOperations(for: splitString(valueA), sharedBox: resultA)
let opsB = stringAppendingBlockOperations(for: splitString(valueB), sharedBox: resultB)
let opsC = stringAppendingBlockOperations(for: splitString(valueC), sharedBox: resultC)
subGroupQueue.isSuspended = true
subGroupQueue.addOperations(opsA, withKey: keyA, waitUntilFinished: false)
subGroupQueue.addOperations(opsB, withKey: keyB, waitUntilFinished: false)
subGroupQueue.addOperations(opsC, withKey: keyC, waitUntilFinished: false)
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[keyA].count == 0)
XCTAssert(subGroupQueue[keyB].count == 0)
XCTAssert(subGroupQueue[keyC].count == 0)
XCTAssert(resultA.value == valueA, "\(resultA.value) didn't match expected value \(valueA)")
XCTAssert(resultB.value == valueB, "\(resultB.value) didn't match expected value \(valueB)")
XCTAssert(resultC.value == valueC, "\(resultC.value) didn't match expected value \(valueC)")
}
// MARK: - addOperation
func testAddOperationWithBlock_withSingleGroup_mustExecuteSerially() {
let (key, value, result) = ("key", "123456", Box<String>(""))
let blocks = stringAppendingBlocks(for: splitString(value), sharedBox: result)
subGroupQueue.isSuspended = true
blocks.forEach { subGroupQueue.addOperation($0, withKey: key) }
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[key].count == 0)
XCTAssert(result.value == value, "\(result.value) didn't match expected value \(value)")
}
func testAddOperationWithBlock_withMutipleGroups_mustExecuteEachGroupSerially() {
let (keyA, valueA, resultA) = ("A", "123456", Box<String>(""))
let (keyB, valueB, resultB) = (1337, "abcdef", Box<String>(""))
let (keyC, valueC, resultC) = (Date(), "ABCDEF", Box<String>(""))
let blocksA = stringAppendingBlocks(for: splitString(valueA), sharedBox: resultA)
let blocksB = stringAppendingBlocks(for: splitString(valueB), sharedBox: resultB)
let blocksC = stringAppendingBlocks(for: splitString(valueC), sharedBox: resultC)
subGroupQueue.isSuspended = true
// schedule them in order *inside* each subgroup, but *shuffled* between subgroups
subGroupQueue.addOperation(blocksA[0], withKey: keyA)
subGroupQueue.addOperation(blocksB[0], withKey: keyB)
subGroupQueue.addOperation(blocksC[0], withKey: keyC)
subGroupQueue.addOperation(blocksA[1], withKey: keyA)
subGroupQueue.addOperation(blocksB[1], withKey: keyB)
subGroupQueue.addOperation(blocksB[2], withKey: keyB)
subGroupQueue.addOperation(blocksA[2], withKey: keyA)
subGroupQueue.addOperation(blocksC[1], withKey: keyC)
subGroupQueue.addOperation(blocksC[2], withKey: keyC)
subGroupQueue.addOperation(blocksA[3], withKey: keyA)
subGroupQueue.addOperation(blocksB[3], withKey: keyB)
subGroupQueue.addOperation(blocksA[4], withKey: keyA)
subGroupQueue.addOperation(blocksC[3], withKey: keyC)
subGroupQueue.addOperation(blocksB[4], withKey: keyB)
subGroupQueue.addOperation(blocksC[4], withKey: keyC)
subGroupQueue.addOperation(blocksA[5], withKey: keyA)
subGroupQueue.addOperation(blocksB[5], withKey: keyB)
subGroupQueue.addOperation(blocksC[5], withKey: keyC)
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[keyA].count == 0)
XCTAssert(subGroupQueue[keyB].count == 0)
XCTAssert(subGroupQueue[keyC].count == 0)
XCTAssert(resultA.value == valueA, "\(resultA.value) didn't match expected value \(valueA)")
XCTAssert(resultB.value == valueB, "\(resultB.value) didn't match expected value \(valueB)")
XCTAssert(resultC.value == valueC, "\(resultC.value) didn't match expected value \(valueC)")
}
// MARK: - mixed
func testMixedAddOperations_withSingleGroup_mustExecuteEachGroupSerially() {
let (key, value, result) = ("key", "123456", Box<String>(""))
let blocks = stringAppendingBlocks(for: splitString(value), sharedBox: result)
subGroupQueue.isSuspended = true
subGroupQueue.addOperation(BlockOperation(block: blocks[0]), withKey: key)
subGroupQueue.addOperation(BlockOperation(block: blocks[1]), withKey: key)
subGroupQueue.addOperation(blocks[2], withKey: key)
subGroupQueue.addOperation(blocks[3], withKey: key)
let op5 = BlockOperation(block: blocks[4])
let op6 = BlockOperation(block: blocks[5])
subGroupQueue.addOperations([op5, op6], withKey: key, waitUntilFinished: false)
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[key].count == 0)
XCTAssert(result.value == value, "\(result.value) didn't match expected value \(value)")
}
func testMixedAddOperations_withMutipleGroups_mustExecuteEachGroupSerially() {
let (keyA, valueA, resultA) = ("A", "123456", Box<String>(""))
let (keyB, valueB, resultB) = (1337, "abcdef", Box<String>(""))
let (keyC, valueC, resultC) = (Date(), "ABCDEF", Box<String>(""))
let blocksA = stringAppendingBlocks(for: splitString(valueA), sharedBox: resultA)
let blocksB = stringAppendingBlocks(for: splitString(valueB), sharedBox: resultB)
let blocksC = stringAppendingBlocks(for: splitString(valueC), sharedBox: resultC)
let opA5 = BlockOperation(block: blocksA[4])
let opA6 = BlockOperation(block: blocksA[5])
let opB3 = BlockOperation(block: blocksB[2])
let opB4 = BlockOperation(block: blocksB[3])
let opC1 = BlockOperation(block: blocksC[0])
let opC2 = BlockOperation(block: blocksC[1])
subGroupQueue.isSuspended = true
// schedule them in order *inside* each subgroup, but *shuffled* between subgroups
subGroupQueue.addOperation(BlockOperation(block: blocksA[0]), withKey: keyA)
subGroupQueue.addOperation(blocksB[0], withKey: keyB)
subGroupQueue.addOperations([opC1, opC2], withKey: keyC, waitUntilFinished: false)
subGroupQueue.addOperation(BlockOperation(block: blocksA[1]), withKey: keyA)
subGroupQueue.addOperation(blocksB[1], withKey: keyB)
subGroupQueue.addOperations([opB3, opB4], withKey: keyB, waitUntilFinished: false)
subGroupQueue.addOperation(blocksA[2], withKey: keyA)
subGroupQueue.addOperation(BlockOperation(block: blocksC[2]), withKey: keyC)
subGroupQueue.addOperation(blocksA[3], withKey: keyA)
subGroupQueue.addOperations([opA5, opA6], withKey: keyA, waitUntilFinished: false)
subGroupQueue.addOperation(BlockOperation(block: blocksC[3]), withKey: keyC)
subGroupQueue.addOperation(BlockOperation(block: blocksB[4]), withKey: keyB)
subGroupQueue.addOperation(blocksC[4], withKey: keyC)
subGroupQueue.addOperation(BlockOperation(block: blocksB[5]), withKey: keyB)
subGroupQueue.addOperation(blocksC[5], withKey: keyC)
subGroupQueue.isSuspended = false
subGroupQueue.waitUntilAllOperationsAreFinished()
XCTAssert(subGroupQueue[keyA].count == 0)
XCTAssert(subGroupQueue[keyB].count == 0)
XCTAssert(subGroupQueue[keyC].count == 0)
XCTAssert(resultA.value == valueA, "\(resultA.value) didn't match expected value \(valueA)")
XCTAssert(resultB.value == valueB, "\(resultB.value) didn't match expected value \(valueB)")
XCTAssert(resultC.value == valueC, "\(resultC.value) didn't match expected value \(valueC)")
}
// MARK: - subGroupOperations
func testSubGroupOperations_withExistingSubGroupOperations_shouldReturnOperations() {
let key = "key"
let ops = stringAppendingBlockOperations(for: splitString("123456"), sharedBox: Box<String>(""))
subGroupQueue.isSuspended = true
subGroupQueue.addOperation(ops[0], withKey: key)
XCTAssert(subGroupQueue.subGroupOperations(forKey: key) == Array(ops[0..<1]))
subGroupQueue.addOperation(ops[1], withKey: key)
XCTAssert(subGroupQueue.subGroupOperations(forKey: key) == Array(ops[0..<2]))
subGroupQueue.addOperation(ops[2], withKey: key)
XCTAssert(subGroupQueue.subGroupOperations(forKey: key) == Array(ops[0..<3]))
subGroupQueue.addOperations(Array(ops[3...5]), withKey: key, waitUntilFinished: false)
XCTAssert(subGroupQueue.subGroupOperations(forKey: key) == ops)
XCTAssert(subGroupQueue[key].count == 6)
}
func testSubGroupOperations_withNonExistingSubGroupOperations_shouldReturnEmptyArray() {
let key = "key"
XCTAssert(subGroupQueue.subGroupOperations(forKey: key) == [])
XCTAssert(subGroupQueue[key].count == 0)
}
}
|
c3e6979630f2e0ff70eb8c54c7f0234e
| 44.106312 | 104 | 0.68837 | false | false | false | false |
alexwinston/UIViewprint
|
refs/heads/master
|
UIViewprint/ViewController10.swift
|
mit
|
1
|
//
// ViewController10.swift
// Blueprint
//
// Created by Alex Winston on 2/11/16.
// Copyright © 2016 Alex Winston. All rights reserved.
//
import Foundation
import UIKit
infix operator < { associativity left }
func input(placeholder placeholder:String, style:UIViewableStyle = UIViewableStyle(), appearance:((UITextField) -> Void)? = nil) -> UIViewable {
var textField:UITextField?
return input(&textField, placeholder:placeholder, style:style, appearance:appearance)
}
func input(inout id:UITextField?, placeholder:String, var style:UIViewableStyle = UIViewableStyle(), appearance:((UITextField) -> Void)? = nil) -> UIViewable {
let textField = UITextField()
textField.placeholder = placeholder
textField.sizeToFit()
if let appearance = appearance {
appearance(textField)
}
if style.display == nil {
style.display = .Flex(.Row)
}
if style.height != -1 {
style.height = textField.frame.height
}
let viewable = UIViewable(style:style)
viewable.addSubview(textField)
id = textField
return div(style, subviews:[viewable])
}
// UIViewableStyle helper functions
func align(align:UIViewableAlign) -> UIViewableStyle {
return UIViewableStyle(align:align)
}
class ViewController10: UIViewableController {
var instructionsLabel:UIViewable?
var emailTextField:UITextField?
var passwordTextField:UITextField?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Example 6"
self.edgesForExtendedLayout = UIRectEdge.None;
// self.view.addSubview(
// div(align(.Middle(.Left)),
// label(&instructionsLabel, text:"Please enter your login credentials.", style:align(.Top(.Center))).display(.Block),
// div(height(10)),
// div(.Flex(.Row),
// div(style(width:100),
// label("Email", style:align(.Top(.Right)))
// ),
// input(&emailTextField, placeholder:"[email protected]", appearance:roundedCorners)
// ),
// div(.Flex(.Row),
// div(style(width:100),
// label("Password", style:align(.Top(.Right)))
// ),
// input(placeholder:"", appearance:roundedCorners)
// ),
// div(height(10)),
// button("Login", display:.Flex(.Row), touch:login)
// )
// )
self.view.addSubview(
div(.Flex(.Column),
div(),
div(style(padding:(0,right:10,0,left:10)),
input(&emailTextField, placeholder:"Email", style:style(padding:(0,0,bottom:5,0)), appearance:largeFontRoundedCorners),
input(placeholder:"Password", appearance:largeFontRoundedCorners)
),
div(),
div(
button("Login", display:.Flex(.Row), align:.Bottom(.Left), height:80, touch:login)
)
)
)
}
func roundedCorners(textField:UITextField) {
textField.borderStyle = .RoundedRect
}
func login(button:UIButton) {
print(emailTextField!.text)
if let instructionsLabel = instructionsLabel?.subviews[0] as? UILabel {
instructionsLabel.text = "This is a test of the emergency broadcast system"
}
// self.view.subviews[0].setNeedsLayout()
if let superview = instructionsLabel?.superview as? UIViewable {
superview.setNeedsLayout()
}
}
func largeFontRoundedCorners(view:UIView) {
if let textField = view as? UITextField {
textField.borderStyle = .RoundedRect
textField.frame.size.height = 54
textField.font = UIFont(name: "HelveticaNeue-Light", size: 26)
textField.returnKeyType = .Done
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.debugSubviews(self.view, indent: "")
}
}
|
716a8bee09860a38e673e96d2a2b15c4
| 32.520325 | 159 | 0.584668 | false | false | false | false |
appculture/MissionControl-iOS
|
refs/heads/master
|
Example/MissionControlDemo/BaseLaunchView.swift
|
mit
|
1
|
//
// BaseLaunchView.swift
// MissionControlDemo
//
// Copyright (c) 2016 appculture <[email protected]> http://appculture.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
@IBDesignable
class BaseLaunchView: UIView {
// MARK: - Outlets
let gradient = UIView()
let gradientLayer = CAGradientLayer()
let button = UIView()
let buttonImage = UIImageView()
let buttonTitle = UILabel()
let statusTitle = UILabel()
let statusLight = UIView()
let countdown = UILabel()
// MARK: - Properties
var didTapButtonAction: ((sender: AnyObject) -> Void)?
var padding: CGFloat = 24.0
var buttonHighlightColor = UIColor.lightGrayColor()
var buttonColor = UIColor.whiteColor() {
didSet {
button.backgroundColor = buttonColor
}
}
var buttonTitleColor = UIColor.darkGrayColor() {
didSet {
buttonTitle.textColor = buttonTitleColor
}
}
var statusLightColor = UIColor.darkGrayColor() {
didSet {
statusLight.backgroundColor = statusLightColor
}
}
var statusTitleColor = UIColor.whiteColor() {
didSet {
statusTitle.textColor = statusTitleColor
statusLight.layer.borderColor = statusTitleColor.CGColor
}
}
var countdownColor = UIColor.whiteColor() {
didSet {
countdown.textColor = countdownColor
}
}
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
init() {
super.init(frame: CGRectZero)
commonInit()
}
func commonInit() {
configureOutlets()
configureHierarchy()
updateConstraints()
}
// MARK: - Override
override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
gradientLayer.frame = gradient.bounds
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if touchesInsideView(touches, view: button) {
highlightButton()
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
if !touchesInsideView(touches, view: button) {
restoreButton()
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
if touchesInsideView(touches, view: button) {
restoreButton()
if let action = didTapButtonAction {
action(sender: button)
}
}
}
private func touchesInsideView(touches: Set<UITouch>, view: UIView) -> Bool {
guard let touch = touches.first else { return false }
let location = touch.locationInView(view)
let insideView = CGRectContainsPoint(view.bounds, location)
return insideView
}
private func highlightButton() {
UIView.animateWithDuration(0.2, animations: { [unowned self] in
self.button.backgroundColor = self.buttonHighlightColor
self.buttonImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
})
}
private func restoreButton() {
UIView.animateWithDuration(0.2, animations: { [unowned self] in
self.button.backgroundColor = self.buttonColor
self.buttonImage.transform = CGAffineTransformIdentity
})
}
// MARK: - Configure Outlets
private func configureOutlets() {
configureGradient()
configureButton()
configureStatus()
configureCountdown()
}
private func configureGradient() {
gradient.translatesAutoresizingMaskIntoConstraints = false
gradient.layer.insertSublayer(gradientLayer, atIndex: 0)
gradientLayer.colors = [UIColor.orangeColor().CGColor, UIColor.blueColor().CGColor]
gradientLayer.contentsScale = UIScreen.mainScreen().scale
gradientLayer.drawsAsynchronously = true
gradientLayer.needsDisplayOnBoundsChange = true
gradientLayer.setNeedsDisplay()
}
private func configureButton() {
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = buttonColor
button.layer.borderColor = statusLightColor.CGColor
button.layer.borderWidth = 10.0
button.layer.cornerRadius = 10.0
button.clipsToBounds = true
buttonImage.translatesAutoresizingMaskIntoConstraints = false
buttonImage.contentMode = .ScaleAspectFill
buttonImage.image = UIImage(named: "appculture")
buttonTitle.translatesAutoresizingMaskIntoConstraints = false
buttonTitle.adjustsFontSizeToFitWidth = true
buttonTitle.textAlignment = .Center
buttonTitle.textColor = buttonTitleColor
buttonTitle.text = "BUTTON"
}
private func configureStatus() {
statusTitle.translatesAutoresizingMaskIntoConstraints = false
statusTitle.setContentHuggingPriority(251.0, forAxis: .Vertical)
statusTitle.adjustsFontSizeToFitWidth = true
statusTitle.textAlignment = .Center
statusTitle.textColor = statusTitleColor
statusTitle.text = "STATUS"
statusLight.translatesAutoresizingMaskIntoConstraints = false
statusLight.backgroundColor = statusLightColor
statusLight.layer.borderColor = statusTitleColor.CGColor
statusLight.layer.borderWidth = 2.0
statusLight.layer.cornerRadius = 16.0
}
private func configureCountdown() {
countdown.translatesAutoresizingMaskIntoConstraints = false
countdown.adjustsFontSizeToFitWidth = true
countdown.textAlignment = .Center
countdown.textColor = countdownColor
countdown.text = "00"
}
// MARK: - Configure Layout
private func configureHierarchy() {
button.addSubview(buttonImage)
button.addSubview(buttonTitle)
gradient.addSubview(button)
gradient.addSubview(statusTitle)
gradient.addSubview(statusLight)
gradient.addSubview(countdown)
addSubview(gradient)
}
override func updateConstraints() {
removeConstraints(constraints)
addConstraints(allConstraints)
super.updateConstraints()
}
// MARK: - Constraints
private var allConstraints: [NSLayoutConstraint] {
var constraints = gradientConstraints
constraints += buttonConstraints + buttonImageConstraints + buttonTitleConstraints
constraints += statusTitleConstraints + statusLightConstraints
constraints += countdownConstraints
return constraints
}
private var gradientConstraints: [NSLayoutConstraint] {
let leading = gradient.leadingAnchor.constraintEqualToAnchor(leadingAnchor)
let trailing = gradient.trailingAnchor.constraintEqualToAnchor(trailingAnchor)
let top = gradient.topAnchor.constraintEqualToAnchor(topAnchor)
let bottom = gradient.bottomAnchor.constraintEqualToAnchor(bottomAnchor)
return [leading, trailing, top, bottom]
}
private var buttonConstraints: [NSLayoutConstraint] {
let leading = button.leadingAnchor.constraintEqualToAnchor(leadingAnchor, constant: padding)
let trailing = button.trailingAnchor.constraintEqualToAnchor(trailingAnchor, constant: -padding)
let bottom = button.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -padding)
let height = button.heightAnchor.constraintEqualToConstant(90.0)
return [leading, trailing, bottom, height]
}
private var buttonImageConstraints: [NSLayoutConstraint] {
let leading = buttonImage.leadingAnchor.constraintEqualToAnchor(button.leadingAnchor, constant: 20.0)
let top = buttonImage.topAnchor.constraintEqualToAnchor(button.topAnchor, constant: 22.0)
let bottom = buttonImage.bottomAnchor.constraintEqualToAnchor(button.bottomAnchor, constant: -22.0)
let width = buttonImage.widthAnchor.constraintEqualToAnchor(buttonImage.heightAnchor)
return [leading, top, bottom, width]
}
private var buttonTitleConstraints: [NSLayoutConstraint] {
let leading = buttonTitle.leadingAnchor.constraintEqualToAnchor(buttonImage.trailingAnchor, constant: 12.0)
let trailing = buttonTitle.trailingAnchor.constraintEqualToAnchor(button.trailingAnchor, constant: -22.0)
let centerY = buttonTitle.centerYAnchor.constraintEqualToAnchor(button.centerYAnchor)
return [leading, trailing, centerY]
}
private var statusTitleConstraints: [NSLayoutConstraint] {
let leading = statusTitle.leadingAnchor.constraintEqualToAnchor(button.leadingAnchor)
let trailing = statusTitle.trailingAnchor.constraintEqualToAnchor(button.trailingAnchor)
let bottom = statusTitle.bottomAnchor.constraintEqualToAnchor(button.topAnchor, constant: -padding)
return [leading, trailing, bottom]
}
private var statusLightConstraints: [NSLayoutConstraint] {
let centerX = statusLight.centerXAnchor.constraintEqualToAnchor(centerXAnchor)
let bottom = statusLight.bottomAnchor.constraintEqualToAnchor(statusTitle.topAnchor, constant: -padding)
let width = statusLight.widthAnchor.constraintEqualToConstant(32.0)
let height = statusLight.heightAnchor.constraintEqualToConstant(32.0)
return [centerX, bottom, width, height]
}
private var countdownConstraints: [NSLayoutConstraint] {
let leading = countdown.leadingAnchor.constraintEqualToAnchor(leadingAnchor)
let trailing = countdown.trailingAnchor.constraintEqualToAnchor(trailingAnchor)
let top = countdown.topAnchor.constraintEqualToAnchor(topAnchor)
let bottom = countdown.bottomAnchor.constraintEqualToAnchor(statusLight.topAnchor)
return [leading, trailing, top, bottom]
}
// MARK: - Interface Builder
override func prepareForInterfaceBuilder() {
let bundle = NSBundle(forClass: self.dynamicType)
let image = UIImage(named: "appculture", inBundle: bundle, compatibleWithTraitCollection: traitCollection)
buttonImage.image = image
}
}
extension UIColor {
// MARK: - HEX Color
convenience init (hex: String) {
var colorString: String = hex
if (hex.hasPrefix("#")) {
let index = hex.startIndex.advancedBy(1)
colorString = colorString.substringFromIndex(index)
}
var rgbValue:UInt32 = 0
NSScanner(string: colorString).scanHexInt(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
|
6cccc2f009f4074f63d240210f50402a
| 35.759644 | 115 | 0.677833 | false | false | false | false |
eBardX/XestiMonitors
|
refs/heads/master
|
Sources/Core/UIKit/Other/PasteboardMonitor.swift
|
mit
|
1
|
//
// PasteboardMonitor.swift
// XestiMonitors
//
// Created by Paul Nyondo on 2018-03-15.
//
// © 2018 J. G. Pusey (see LICENSE.md)
//
#if os(iOS)
import UIKit
///
/// A `PasteboardMonitor` instance monitors a pasteboard for changes to its
/// contents or for its removal from the app.
///
public class PasteboardMonitor: BaseNotificationMonitor {
///
/// Encapsulates information associated with a pasteboard monitor
/// `changed` event.
///
public struct Changes {
///
/// The representation types of items that have been added to the
/// pasteboard.
///
public let typesAdded: [String]
///
/// The representation types of items that have been removed from
/// the pasteboard.
///
public let typesRemoved: [String]
fileprivate init(_ userInfo: [AnyHashable: Any]?) {
self.typesAdded = userInfo?[UIPasteboardChangedTypesAddedKey] as? [String] ?? []
self.typesRemoved = userInfo?[UIPasteboardChangedTypesRemovedKey] as? [String] ?? []
}
}
///
/// Encapsulates changes to the pasteboard and its contents.
///
public enum Event {
///
/// The contents of the pasteboard have changed.
///
case changed(UIPasteboard, Changes)
///
/// The pasteboard has been removed from the app.
///
case removed(UIPasteboard)
}
///
/// Specifies which events to monitor.
///
public struct Options: OptionSet {
///
/// Monitor `changed` events.
///
public static let changed = Options(rawValue: 1 << 0)
///
/// Monitor `removed` events.
///
public static let removed = Options(rawValue: 1 << 1)
///
/// Monitor all events.
///
public static let all: Options = [.changed,
.removed]
/// :nodoc:
public init(rawValue: UInt) {
self.rawValue = rawValue
}
/// :nodoc:
public let rawValue: UInt
}
///
/// Initializes a new `PasteboardMonitor`.
///
/// - Parameters:
/// - pasteboard: The pasteboard to monitor.
/// - options: The options that specify which events to monitor.
/// By default all events are monitored
/// - queue: The operation queue on which the handler executes.
/// By default, the main operation queue is used.
/// - handler: The handler to call when the pasteboard is removed
/// from the app, or its contents change.
///
public init(pasteboard: UIPasteboard,
options: Options = .all,
queue: OperationQueue = .main,
handler: @escaping(Event) -> Void) {
self.handler = handler
self.options = options
self.pasteboard = pasteboard
super.init(queue: queue)
}
///
/// The pasteboard being monitored.
///
public let pasteboard: UIPasteboard
private let handler: (Event) -> Void
private let options: Options
override public func addNotificationObservers() {
super.addNotificationObservers()
if options.contains(.changed) {
observe(.UIPasteboardChanged,
object: pasteboard) { [unowned self] in
if let pasteboard = $0.object as? UIPasteboard {
self.handler(.changed(pasteboard, Changes($0.userInfo)))
}
}
}
if options.contains(.removed) {
observe(.UIPasteboardRemoved,
object: pasteboard) { [unowned self] in
if let pasteboard = $0.object as? UIPasteboard {
self.handler(.removed(pasteboard))
}
}
}
}
}
#endif
|
09bfd2a49e68294b86e12d9d0edac634
| 27.371429 | 96 | 0.54003 | false | false | false | false |
sdulal/swift
|
refs/heads/master
|
test/SILGen/builtins.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | FileCheck %s
// RUN: %target-swift-frontend -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | FileCheck -check-prefix=CANONICAL %s
import Swift
protocol ClassProto : class { }
struct Pointer {
var value: Builtin.RawPointer
}
// CHECK-LABEL: sil hidden @_TF8builtins3foo
func foo(x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 {
// CHECK: builtin "cmp_eq_Int1"
return Builtin.cmp_eq_Int1(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8load_pod
func load_pod(x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8load_obj
func load_obj(x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK: retain [[VAL]]
// CHECK: return [[VAL]]
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8load_gen
func load_gen<T>(x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}}
return Builtin.load(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8move_pod
func move_pod(x: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8move_obj
func move_obj(x: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: [[VAL:%.*]] = load [[ADDR]]
// CHECK-NOT: retain [[VAL]]
// CHECK: return [[VAL]]
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins8move_gen
func move_gen<T>(x: Builtin.RawPointer) -> T {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}}
return Builtin.take(x)
}
// CHECK-LABEL: sil hidden @_TF8builtins11destroy_pod
func destroy_pod(x: Builtin.RawPointer) {
var x = x
// CHECK: [[X:%[0-9]+]] = alloc_box
// CHECK-NOT: pointer_to_address
// CHECK-NOT: destroy_addr
// CHECK-NOT: release
// CHECK: release [[X]]#0 : $@box
// CHECK-NOT: release
return Builtin.destroy(Builtin.Int64, x)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8builtins11destroy_obj
func destroy_obj(x: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(Builtin.NativeObject, x)
}
// CHECK-LABEL: sil hidden @_TF8builtins11destroy_gen
func destroy_gen<T>(x: Builtin.RawPointer, _: T) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: destroy_addr [[ADDR]]
return Builtin.destroy(T.self, x)
}
// CHECK-LABEL: sil hidden @_TF8builtins10assign_pod
func assign_pod(x: Builtin.Int64, y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: alloc_box
// CHECK: alloc_box
// CHECK-NOT: alloc_box
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: release
// CHECK: release
// CHECK-NOT: release
Builtin.assign(x, y)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF8builtins10assign_obj
func assign_obj(x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: release
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins12assign_tuple
func assign_tuple(x: (Builtin.Int64, Builtin.NativeObject),
y: Builtin.RawPointer) {
var x = x
var y = y
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*(Builtin.Int64, Builtin.NativeObject)
// CHECK: assign {{%.*}} to [[ADDR]]
// CHECK: release
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins10assign_gen
func assign_gen<T>(x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [take] {{%.*}} to [[ADDR]] :
Builtin.assign(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8init_pod
func init_pod(x: Builtin.Int64, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64
// CHECK-NOT: load [[ADDR]]
// CHECK: store {{%.*}} to [[ADDR]]
// CHECK-NOT: release [[ADDR]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8init_obj
func init_obj(x: Builtin.NativeObject, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject
// CHECK-NOT: load [[ADDR]]
// CHECK: store [[SRC:%.*]] to [[ADDR]]
// CHECK-NOT: release [[SRC]]
Builtin.initialize(x, y)
}
// CHECK-LABEL: sil hidden @_TF8builtins8init_gen
func init_gen<T>(x: T, y: Builtin.RawPointer) {
// CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*T
// CHECK: copy_addr [take] {{%.*}} to [initialization] [[ADDR]]
Builtin.initialize(x, y)
}
class C {}
class D {}
// CHECK-LABEL: sil hidden @_TF8builtins22class_to_native_object
func class_to_native_object(c:C) -> Builtin.NativeObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins23class_to_unknown_object
func class_to_unknown_object(c:C) -> Builtin.UnknownObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToUnknownObject(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins32class_archetype_to_native_object
func class_archetype_to_native_object<T : C>(t: T) -> Builtin.NativeObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins33class_archetype_to_unknown_object
func class_archetype_to_unknown_object<T : C>(t: T) -> Builtin.UnknownObject {
// CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[OBJ]]
return Builtin.castToUnknownObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins34class_existential_to_native_object
func class_existential_to_native_object(t:ClassProto) -> Builtin.NativeObject {
// CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto
// CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject
return Builtin.castToNativeObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins35class_existential_to_unknown_object
func class_existential_to_unknown_object(t:ClassProto) -> Builtin.UnknownObject {
// CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto
// CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject
return Builtin.castToUnknownObject(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins24class_from_native_object
func class_from_native_object(p: Builtin.NativeObject) -> C {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins25class_from_unknown_object
func class_from_unknown_object(p: Builtin.UnknownObject) -> C {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins34class_archetype_from_native_object
func class_archetype_from_native_object<T : C>(p: Builtin.NativeObject) -> T {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins35class_archetype_from_unknown_object
func class_archetype_from_unknown_object<T : C>(p: Builtin.UnknownObject) -> T {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins41objc_class_existential_from_native_object
func objc_class_existential_from_native_object(p: Builtin.NativeObject) -> AnyObject {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromNativeObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins42objc_class_existential_from_unknown_object
func objc_class_existential_from_unknown_object(p: Builtin.UnknownObject) -> AnyObject {
// CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject
// CHECK-NOT: release [[C]]
// CHECK-NOT: release [[OBJ]]
// CHECK: return [[C]]
return Builtin.castFromUnknownObject(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins20class_to_raw_pointer
func class_to_raw_pointer(c: C) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
func class_archetype_to_raw_pointer<T : C>(t: T) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(t)
}
protocol CP: class {}
func existential_to_raw_pointer(p: CP) -> Builtin.RawPointer {
return Builtin.bridgeToRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins18obj_to_raw_pointer
func obj_to_raw_pointer(c: Builtin.NativeObject) -> Builtin.RawPointer {
// CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer
// CHECK: return [[RAW]]
return Builtin.bridgeToRawPointer(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins22class_from_raw_pointer
func class_from_raw_pointer(p: Builtin.RawPointer) -> C {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
func class_archetype_from_raw_pointer<T : C>(p: Builtin.RawPointer) -> T {
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins20obj_from_raw_pointer
func obj_from_raw_pointer(p: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins28unknown_obj_from_raw_pointer
func unknown_obj_from_raw_pointer(p: Builtin.RawPointer) -> Builtin.UnknownObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins28existential_from_raw_pointer
func existential_from_raw_pointer(p: Builtin.RawPointer) -> AnyObject {
// CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject
// CHECK: retain [[C]]
// CHECK: return [[C]]
return Builtin.bridgeFromRawPointer(p)
}
// CHECK-LABEL: sil hidden @_TF8builtins5gep64
func gep64(p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gep_Int64(p, i)
}
// CHECK-LABEL: sil hidden @_TF8builtins5gep32
func gep32(p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer {
// CHECK: [[GEP:%.*]] = index_raw_pointer
// CHECK: return [[GEP]]
return Builtin.gep_Int32(p, i)
}
// CHECK-LABEL: sil hidden @_TF8builtins8condfail
func condfail(i: Builtin.Int1) {
Builtin.condfail(i)
// CHECK: cond_fail {{%.*}} : $Builtin.Int1
}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: sil hidden @_TF8builtins10canBeClass
func canBeClass<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(O.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(OP1.self)
// -- FIXME: protocol<...> doesn't parse as a value
typealias ObjCCompo = protocol<OP1, OP2>
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(ObjCCompo.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(S.self)
// CHECK: integer_literal $Builtin.Int8, 1
Builtin.canBeClass(C.self)
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(P.self)
typealias MixedCompo = protocol<OP1, P>
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompo.self)
// CHECK: builtin "canBeClass"<T>
Builtin.canBeClass(T.self)
}
// FIXME: "T.Type.self" does not parse as an expression
// CHECK-LABEL: sil hidden @_TF8builtins18canBeClassMetatype
func canBeClassMetatype<T>(_: T) {
// CHECK: integer_literal $Builtin.Int8, 0
typealias OT = O.Type
Builtin.canBeClass(OT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias OP1T = OP1.Type
Builtin.canBeClass(OP1T.self)
// -- FIXME: protocol<...> doesn't parse as a value
typealias ObjCCompoT = protocol<OP1, OP2>.Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(ObjCCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias ST = S.Type
Builtin.canBeClass(ST.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias CT = C.Type
Builtin.canBeClass(CT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias PT = P.Type
Builtin.canBeClass(PT.self)
typealias MixedCompoT = protocol<OP1, P>.Type
// CHECK: integer_literal $Builtin.Int8, 0
Builtin.canBeClass(MixedCompoT.self)
// CHECK: integer_literal $Builtin.Int8, 0
typealias TT = T.Type
Builtin.canBeClass(TT.self)
}
// CHECK-LABEL: sil hidden @_TF8builtins11fixLifetime
func fixLifetime(c: C) {
// CHECK: fix_lifetime %0 : $C
Builtin.fixLifetime(c)
}
// CHECK-LABEL: sil hidden @_TF8builtins20assert_configuration
func assert_configuration() -> Builtin.Int32 {
return Builtin.assert_configuration()
// CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32
// CHECK: return [[APPLY]] : $Builtin.Int32
}
// CHECK-LABEL: sil hidden @_TF8builtins17assumeNonNegativeFBwBw
func assumeNonNegative(x: Builtin.Word) -> Builtin.Word {
return Builtin.assumeNonNegative_Word(x)
// CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word
// CHECK: return [[APPLY]] : $Builtin.Word
}
// CHECK-LABEL: sil hidden @_TF8builtins11autorelease
// CHECK: autorelease_value %0
func autorelease(o: O) {
Builtin.autorelease(o)
}
// The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during
// diagnostics.
// CHECK-LABEL: sil hidden @_TF8builtins11unreachable
// CHECK: builtin "unreachable"()
// CHECK: return
// CANONICAL-LABEL: sil hidden @_TF8builtins11unreachableFT_T_ : $@convention(thin) @noreturn () -> () {
// CANONICAL-NOT: builtin "unreachable"
// CANONICAL-NOT: return
// CANONICAL: unreachable
@noreturn func unreachable() {
Builtin.unreachable()
}
// CHECK-LABEL: sil hidden @_TF8builtins15reinterpretCastFTCS_1C1xBw_TBwCS_1DGSqS0__S0__ : $@convention(thin) (@owned C, Builtin.Word) -> @owned (Builtin.Word, D, Optional<C>, C)
// CHECK: bb0(%0 : $C, %1 : $Builtin.Word):
// CHECK-NEXT: debug_value
// CHECK-NEXT: debug_value
// CHECK-NEXT: strong_retain %0 : $C
// CHECK-NEXT: unchecked_trivial_bit_cast %0 : $C to $Builtin.Word
// CHECK-NEXT: unchecked_ref_cast %0 : $C to $D
// CHECK-NEXT: unchecked_ref_cast %0 : $C to $Optional<C>
// CHECK-NEXT: unchecked_bitwise_cast %1 : $Builtin.Word to $C
// CHECK-NEXT: strong_retain %{{.*}} : $C
// CHECK-NOT: strong_retain
// CHECK-NOT: strong_release
// CHECK-NOT: release_value
// CHECK: return
func reinterpretCast(c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) {
return (Builtin.reinterpretCast(c) as Builtin.Word,
Builtin.reinterpretCast(c) as D,
Builtin.reinterpretCast(c) as C?,
Builtin.reinterpretCast(x) as C)
}
// CHECK-LABEL: sil hidden @_TF8builtins19reinterpretAddrOnly
func reinterpretAddrOnly<T, U>(t: T) -> U {
// CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins28reinterpretAddrOnlyToTrivial
func reinterpretAddrOnlyToTrivial<T>(t: T) -> Int {
// CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int
// CHECK: [[VALUE:%.*]] = load [[ADDR]]
// CHECK: destroy_addr [[INPUT]]
return Builtin.reinterpretCast(t)
}
// CHECK-LABEL: sil hidden @_TF8builtins27reinterpretAddrOnlyLoadable
func reinterpretAddrOnlyLoadable<T>(a: Int, _ b: T) -> (T, Int) {
// CHECK: [[BUF:%.*]] = alloc_stack $Int
// CHECK: store {{%.*}} to [[BUF]]#1
// CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]]#1 : $*Int to $*T
// CHECK: copy_addr [[RES1]] to [initialization]
return (Builtin.reinterpretCast(a) as T,
// CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int
// CHECK: load [[RES]]
Builtin.reinterpretCast(b) as Int)
}
// CHECK-LABEL: sil hidden @_TF8builtins18castToBridgeObject
// CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word
// CHECK: return [[BO]]
func castToBridgeObject(c: C, _ w: Builtin.Word) -> Builtin.BridgeObject {
return Builtin.castToBridgeObject(c, w)
}
// CHECK-LABEL: sil hidden @_TF8builtins23castRefFromBridgeObject
// CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C
func castRefFromBridgeObject(bo: Builtin.BridgeObject) -> C {
return Builtin.castReferenceFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden @_TF8builtins30castBitPatternFromBridgeObject
// CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word
// CHECK: release [[BO]]
func castBitPatternFromBridgeObject(bo: Builtin.BridgeObject) -> Builtin.Word {
return Builtin.castBitPatternFromBridgeObject(bo)
}
// CHECK-LABEL: sil hidden @_TF8builtins14markDependence
// CHECK: [[T0:%.*]] = mark_dependence %0 : $Pointer on %1 : $ClassProto
// CHECK-NEXT: strong_release %1 : $ClassProto
// CHECK-NEXT: return [[T0]] : $Pointer
func markDependence(v: Pointer, _ base: ClassProto) -> Pointer {
return Builtin.markDependence(v, base)
}
// CHECK-LABEL: sil hidden @_TF8builtins8pinUnpin
// CHECK: bb0(%0 : $Builtin.NativeObject):
// CHECK-NEXT: debug_value
func pinUnpin(object : Builtin.NativeObject) {
// CHECK-NEXT: strong_retain %0 : $Builtin.NativeObject
// CHECK-NEXT: [[HANDLE:%.*]] = strong_pin %0 : $Builtin.NativeObject
// CHECK-NEXT: debug_value
// CHECK-NEXT: strong_release %0 : $Builtin.NativeObject
let handle : Builtin.NativeObject? = Builtin.tryPin(object)
// CHECK-NEXT: retain_value [[HANDLE]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_unpin [[HANDLE]] : $Optional<Builtin.NativeObject>
Builtin.unpin(handle)
// CHECK-NEXT: tuple ()
// CHECK-NEXT: release_value [[HANDLE]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_release %0 : $Builtin.NativeObject
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
}
// CHECK-LABEL: sil hidden @_TF8builtins19allocateValueBuffer
// CHECK: bb0([[BUFFER:%.*]] : $*Builtin.UnsafeValueBuffer):
// CHECK-NEXT: metatype $@thin Int.Type
// CHECK-NEXT: [[T0:%.*]] = alloc_value_buffer $Int in [[BUFFER]] : $*Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK-NEXT: return [[T1]] : $Builtin.RawPointer
func allocateValueBuffer(inout buffer: Builtin.UnsafeValueBuffer) -> Builtin.RawPointer {
return Builtin.allocValueBuffer(&buffer, Int.self)
}
// CHECK-LABEL: sil hidden @_TF8builtins18projectValueBuffer
// CHECK: bb0([[BUFFER:%.*]] : $*Builtin.UnsafeValueBuffer):
// CHECK-NEXT: metatype $@thin Int.Type
// CHECK-NEXT: [[T0:%.*]] = project_value_buffer $Int in [[BUFFER]] : $*Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK-NEXT: return [[T1]] : $Builtin.RawPointer
func projectValueBuffer(inout buffer: Builtin.UnsafeValueBuffer) -> Builtin.RawPointer {
return Builtin.projectValueBuffer(&buffer, Int.self)
}
// CHECK-LABEL: sil hidden @_TF8builtins18deallocValueBuffer
// CHECK: bb0([[BUFFER:%.*]] : $*Builtin.UnsafeValueBuffer):
// CHECK-NEXT: metatype $@thin Int.Type
// CHECK-NEXT: dealloc_value_buffer $Int in [[BUFFER]] : $*Builtin.UnsafeValueBuffer
// CHECK-NEXT: tuple ()
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
func deallocValueBuffer(inout buffer: Builtin.UnsafeValueBuffer) -> () {
Builtin.deallocValueBuffer(&buffer, Int.self)
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// NativeObject
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.NativeObject>
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Builtin.NativeObject>
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.NativeObject?) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// NativeObject nonNull
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.NativeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.NativeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.NativeObject
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.NativeObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// NativeObject pinned
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.NativeObject>
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Optional<Builtin.NativeObject>
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Optional<Builtin.NativeObject>
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Builtin.NativeObject>
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.NativeObject?) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// NativeObject pinned nonNull
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Builtin.NativeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.NativeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.NativeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.NativeObject
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.NativeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// UnknownObject (ObjC)
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Optional<Builtin.UnknownObject>
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Optional<Builtin.UnknownObject>
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Optional<Builtin.UnknownObject>
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Optional<Builtin.UnknownObject>
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Optional<Builtin.UnknownObject>
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.UnknownObject?) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// UnknownObject (ObjC) nonNull
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Builtin.UnknownObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.UnknownObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.UnknownObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.UnknownObject
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.UnknownObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// UnknownObject (ObjC) pinned nonNull
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Builtin.UnknownObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.UnknownObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Builtin.UnknownObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.UnknownObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.UnknownObject
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.UnknownObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// BridgeObject nonNull
// CHECK-LABEL: sil hidden @_TF8builtins8isUnique
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUnique(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUnique(&ref))
}
// BridgeObject pinned nonNull
// CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUniqueOrPinned(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned(&ref))
}
// BridgeObject nonNull native
// CHECK-LABEL: sil hidden @_TF8builtins15isUnique_native
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[CAST:%.*]] = unchecked_addr_cast [[BOX]]#1 : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique [[CAST]] : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUnique_native(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUnique_native(&ref))
}
// BridgeObject pinned nonNull native
// CHECK-LABEL: sil hidden @_TF8builtins23isUniqueOrPinned_native
// CHECK: bb0(%0 : $*Builtin.BridgeObject):
// CHECK-NEXT: [[BOX:%.*]] = alloc_box $Builtin.BridgeObject
// CHECK: copy_addr %0 to [initialization] [[BOX]]#1 : $*Builtin.BridgeObject
// CHECK: [[CAST:%.*]] = unchecked_addr_cast [[BOX]]#1 : $*Builtin.BridgeObject to $*Builtin.NativeObject
// CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject
// CHECK: copy_addr [[BOX]]#1 to %0 : $*Builtin.BridgeObject
// CHECK-NEXT: strong_release [[BOX]]#0 : $@box Builtin.BridgeObject
// CHECK-NEXT: return
func isUniqueOrPinned_native(inout ref: Builtin.BridgeObject) -> Bool {
return _getBool(Builtin.isUniqueOrPinned_native(&ref))
}
// ----------------------------------------------------------------------------
// Builtin.castReference
// ----------------------------------------------------------------------------
class A {}
protocol PUnknown {}
protocol PClass : class {}
// CHECK-LABEL: sil hidden @_TF8builtins19refcast_generic_any
// CHECK: unchecked_ref_cast_addr T in %{{.*}}#1 : $*T to AnyObject in %{{.*}}#1 : $*AnyObject
func refcast_generic_any<T>(o: T) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins17refcast_class_any
// CHECK: unchecked_ref_cast %0 : $A to $AnyObject
// CHECK-NEXT: return
func refcast_class_any(o: A) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins20refcast_punknown_any
// CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}}#1 : $*PUnknown to AnyObject in %{{.*}}#1 : $*AnyObject
func refcast_punknown_any(o: PUnknown) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins18refcast_pclass_any
// CHECK: unchecked_ref_cast %0 : $PClass to $AnyObject
// CHECK-NEXT: return
func refcast_pclass_any(o: PClass) -> AnyObject {
return Builtin.castReference(o)
}
// CHECK-LABEL: sil hidden @_TF8builtins20refcast_any_punknown
// CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}}#1 : $*AnyObject to PUnknown in %{{.*}}#1 : $*PUnknown
func refcast_any_punknown(o: AnyObject) -> PUnknown {
return Builtin.castReference(o)
}
|
fcee05dff7d217a883e6c08942069459
| 38.62141 | 178 | 0.663954 | false | false | false | false |
weiyanwu84/MLSwiftBasic
|
refs/heads/master
|
MLSwiftBasic/Classes/PhotoPicker/MLPhotoPickerDAO.swift
|
mit
|
1
|
//
// MLPhotoPickerDAO.swift
// MLSwiftBasic
//
// Created by 张磊 on 15/8/27.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
import AssetsLibrary
let MLPhotoPickerBundleName = "MLPhotoPicker.bundle"
class MLPhotoGroup: NSObject {
/// ALAssetsGroup
var group:ALAssetsGroup!
/// ALAssetsGroup Name
lazy var groupName:String = {
return self.group.valueForProperty("ALAssetsGroupPropertyName") as! String
}()
/// ALAssetsGroup ThumbImage
lazy var thumbImage:UIImage = {
return UIImage(CGImage: self.group.posterImage().takeUnretainedValue())!
}()
/// ALAssetsGroup subAssetsCount
lazy var assetsCount:NSInteger = {
return self.group.numberOfAssets()
}()
/// Init
init(group:ALAssetsGroup) {
super.init()
self.group = group
}
}
class MLPhotoPickerDAO: NSObject {
/// Signle AssetsLibrary Object.
class var sharedDAO:MLPhotoPickerDAO{
struct staic {
static var onceToken:dispatch_once_t = 0
static var instance:MLPhotoPickerDAO?
}
dispatch_once(&staic.onceToken, { () -> Void in
staic.instance = MLPhotoPickerDAO()
})
return staic.instance!
}
var sharedAssetsLibrary:ALAssetsLibrary{
struct staic {
static var onceToken:dispatch_once_t = 0
static var instance:ALAssetsLibrary?
}
dispatch_once(&staic.onceToken, { () -> Void in
staic.instance = ALAssetsLibrary()
})
return staic.instance!
}
/**
获取所有的Group模型
:param: groups 数组
*/
func getAllGroups(groupsCallBack :((groups:Array<MLPhotoGroup>) -> Void)){
var groups:NSMutableArray = NSMutableArray()
var resultBlock:ALAssetsLibraryGroupsEnumerationResultsBlock = { (group, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
if group != nil {
var gp = MLPhotoGroup(group: group)
groups.addObject(gp)
}else{
var tempGroups = NSArray(array: groups)
groupsCallBack(groups:tempGroups as! Array<MLPhotoGroup>)
}
}
self.sharedAssetsLibrary.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock:resultBlock, failureBlock: nil)
}
/**
获取所有的Group模型
:param: groups 数组
*/
func getAllAssetsWithGroup(group:MLPhotoGroup, assetsCallBack :((assets:Array<MLPhotoAssets>) -> Void)){
var assets:NSMutableArray = NSMutableArray()
var resultBlock:ALAssetsGroupEnumerationResultsBlock = { (asset, index, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
if (asset != nil) {
var photoAssets:MLPhotoAssets = MLPhotoAssets(asset: asset)
assets.addObject(photoAssets)
}else{
var tempAssets = NSArray(array: assets)
assetsCallBack(assets: tempAssets as! Array<MLPhotoAssets>);
}
}
group.group.enumerateAssetsUsingBlock(resultBlock)
}
}
class MLPhotoAssets: NSObject{
var asset:ALAsset!
lazy var thumbImage:UIImage? = {
if self.asset != nil {
return UIImage(CGImage: self.asset!.thumbnail().takeUnretainedValue())!
}else{
return nil
}
}()
/// Init
init(asset:ALAsset?) {
super.init()
self.asset = asset
}
}
|
f008f49f24ccb8ffcaded914104a61a5
| 28.904348 | 128 | 0.612969 | false | false | false | false |
alblue/swift
|
refs/heads/master
|
validation-test/stdlib/HashedCollectionFilter3.swift
|
apache-2.0
|
4
|
// RUN: %target-run-stdlib-swift-swift3
// REQUIRES: executable_test
import StdlibUnittest
var FilterTestSuite = TestSuite("HashedCollectionFilter")
FilterTestSuite.test("Dictionary.filter(_:) -> [(Key, Value)]") {
let d = [10: 1010, 20: 1020, 30: 1030, 40: 1040]
let f: Any = d.filter { (k, v) in k > 20 }
expectTrue(f is [(Int, Int)])
}
FilterTestSuite.test("Set.filter(_:) -> [Element]") {
let s: Set = [10, 20, 30, 40]
let f: Any = s.filter { $0 > 20 }
expectTrue(f is [Int])
}
FilterTestSuite.test("Dictionary.keys -> LazyMapCollection") {
let d = [10: 1010, 20: 1020, 30: 1030, 40: 1040]
// .keys should produce a LazyMapCollection in Swift 3
let f: Any = d.keys
let g = f as! LazyMapCollection<[Int: Int], Int>
expectEqual(4, g.count)
}
FilterTestSuite.test("Dictionary.values -> LazyMapCollection") {
let d = [10: 1010, 20: 1020, 30: 1030, 40: 1040]
// .values should produce a LazyMapCollection in Swift 3
let f: Any = d.values
let g = f as! LazyMapCollection<[Int: Int], Int>
expectEqual(4, g.count)
}
runAllTests()
|
cab967f3d46a093fc677915b8fdc9064
| 27.810811 | 65 | 0.655722 | false | true | false | false |
snownothing/RefreshControl-Swift
|
refs/heads/master
|
RefreshControl/Arrow.swift
|
mit
|
1
|
//
// Arrow.swift
// RefreshControl-Swift
//
// Created by Moch Xiao on 2014-10-13.
// Copyright (c) 2014 Moch Xiao (https://github.com/atcuan).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
let kArrowPointCount = 7
import UIKit
public class Arrow: UIView {
var color: UIColor?
required public init(coder aDecoder: NSCoder) {
self.color = UIColor.lightGrayColor()
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clearColor()
}
override init(frame: CGRect) {
self.color = UIColor.lightGrayColor()
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
override public func drawRect(rect: CGRect) {
let startPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.bounds));
let endPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds));
let tailWidth = CGRectGetWidth(self.bounds) / 3;
let headWidth = CGRectGetWidth(self.bounds) * 0.7;
let headLength = CGRectGetHeight(self.bounds) / 2;
let bezierPath = UIBezierPath.bezierPathWithArrowFromPointStartPoint(startPoint, toPoint: endPoint, tailWidth: tailWidth, headWidth: headWidth, headLength: headLength)
self.color?.setFill()
bezierPath.fill()
}
// MARK: - public methods
public func rotation() {
UIView.animateWithDuration(0.2, animations: {
self.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
})
}
public func identity() {
UIView.animateWithDuration(0.2, animations: {
self.transform = CGAffineTransformIdentity
})
}
}
// MARK: - UIBezierPath extension
public extension UIBezierPath {
public class func bezierPathWithArrowFromPointStartPoint(startPoint: CGPoint, toPoint endPoint: CGPoint, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) -> UIBezierPath {
let xDiff = Float(endPoint.x - startPoint.x)
let yDiff = Float(endPoint.y - startPoint.y)
let length = CGFloat(hypotf(xDiff, yDiff))
var points = [CGPoint](count: Int(kArrowPointCount), repeatedValue: CGPointZero)
self.axisAlignedArrowPoints(&points, forLength: length, tailWidth: tailWidth, headWidth: headWidth, headLength: headLength)
var transform: CGAffineTransform = self.transformForStartPoint(startPoint, endPoint: endPoint, length: length)
var cgPath: CGMutablePathRef = CGPathCreateMutable()
CGPathAddLines(cgPath, &transform, points, 7)
CGPathCloseSubpath(cgPath)
var uiPath: UIBezierPath = UIBezierPath(CGPath: cgPath)
return uiPath
}
private class func axisAlignedArrowPoints(inout points: [CGPoint], forLength length: CGFloat, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) {
let tailLength = length - headLength
points[0] = CGPointMake(0, tailWidth / 2)
points[1] = CGPointMake(tailLength, tailWidth / 2)
points[2] = CGPointMake(tailLength, headWidth / 2)
points[3] = CGPointMake(length, 0)
points[4] = CGPointMake(tailLength, -headWidth / 2)
points[5] = CGPointMake(tailLength, -tailWidth / 2)
points[6] = CGPointMake(0, -tailWidth / 2)
}
private class func transformForStartPoint(startPoint: CGPoint, endPoint: CGPoint, length: CGFloat) -> CGAffineTransform {
let cosine = (endPoint.x - startPoint.x) / length
let sine = (endPoint.y - startPoint.y) / length
return CGAffineTransformMake(cosine, sine, -sine, cosine, startPoint.x, startPoint.y)
}
}
|
59ba82fc4b835d7b9b3021af85779ab0
| 42.592593 | 187 | 0.691801 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.