repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
C39GX6/ArchiveExport | ArchiveExport/AEArchive.swift | 1 | 1984 | //
// AEArchive.swift
// ArchiveExport
//
// Created by 刘诗彬 on 14/10/29.
// Copyright (c) 2014年 Stephen. All rights reserved.
//
import Cocoa
class AEArchive: NSObject {
var createDate : NSDate!
var version : String!
var buildVersion : String!
var identifier : String!
var name : String!
var icon : NSImage!
var appPath : String!
var dateString : String{
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.timeStyle = NSDateFormatterStyle.MediumStyle;
formatter.dateStyle = NSDateFormatterStyle.ShortStyle;
if createDate==nil{
createDate = NSDate();
}
return formatter.stringFromDate(createDate);
}
init(path:String) {
let infoPath = path + "/info.plist"
let info = NSDictionary(contentsOfFile: infoPath)
createDate = info?.objectForKey("CreationDate") as! NSDate
name = info?.objectForKey("Name") as! String
let applicationProperties = info?.objectForKey("ApplicationProperties") as! NSDictionary!
if applicationProperties != nil{
version = applicationProperties.objectForKey("CFBundleShortVersionString") as! String
buildVersion = applicationProperties.objectForKey("CFBundleVersion") as! String
identifier = applicationProperties.objectForKey("CFBundleIdentifier") as! String
let appBundleName = applicationProperties.objectForKey("ApplicationPath") as! String
appPath = path + "/Products/" + appBundleName
let iconPaths = applicationProperties.objectForKey("IconPaths") as! NSArray!
if iconPaths != nil{
let iconName = iconPaths.objectAtIndex(0) as! String
let iconPath = path + "/Products/" + iconName;
icon = NSImage(contentsOfFile: iconPath)
}
}
}
}
| apache-2.0 | 90fce774e5f47d47ba26c194b6f28c1b | 34.285714 | 97 | 0.628543 | 5.227513 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1081-getselftypeforcontainer.swift | 13 | 435 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
func j<f: l: e -> e = {
enum b {
e}
class d<c>: NSObject {
init(b: c) {
}
}
}
protocol l : f { func f
| apache-2.0 | 11196b852e33ef3b1fed61e1a8bf760b | 15.730769 | 87 | 0.574713 | 2.5 | false | true | false | false |
CD1212/Doughnut | Doughnut/Library/TaskQueue.swift | 1 | 2344 | //
// TaskQueue.swift
// Doughnut
//
// Created by Chris Dyer on 02/01/2018.
// Copyright © 2018 Chris Dyer. All rights reserved.
//
import Foundation
protocol TaskProgressDelegate {
func progressed()
}
class Task: NSObject {
let id = NSUUID().uuidString
let name: String
var detailInformation: String? = "Queued"
var progressDelegate: TaskProgressDelegate?
var success: (Any?) -> Void
var failure: (Any?) -> Void
init(name: String) {
self.name = name
success = { object in }
failure = { object in }
super.init()
}
var isIndeterminate: Bool = true
var progressValue: Double = 0
var progressMax: Double = 0
open func perform(queue: DispatchQueue, completion: @escaping (_ success: Bool, _ object: Any?) -> Void) {
queue.async {
sleep(10)
completion(true, nil)
}
}
func emitProgress() {
if let delegate = progressDelegate {
DispatchQueue.main.async {
delegate.progressed()
}
}
}
}
// let task = DownloadTask(episode, porcast)
// task.success =
// Library.global.queue.push(task)
protocol TaskQueueViewDelegate {
func taskPushed(task: Task)
func taskFinished(task: Task)
func tasksRunning(_ running: Bool)
}
class TaskQueue {
let dispatchQueue = DispatchQueue(label: "com.doughnut.Tasks")
var tasks = [Task]()
var delegate: TaskQueueViewDelegate?
fileprivate(set) var running = false {
didSet {
DispatchQueue.main.async {
self.delegate?.tasksRunning(self.running)
}
}
}
var count: Int {
return tasks.count
}
func run(_ task: Task) {
tasks.append(task)
DispatchQueue.main.async {
self.delegate?.taskPushed(task: task)
}
if !running {
running = true
runNextTask()
}
}
func runNextTask() {
var task: Task? = nil
if tasks.count > 0 {
task = tasks.remove(at: 0)
}
if let task = task {
task.perform(queue: dispatchQueue) { (success, object) in
if success {
task.success(object)
} else {
task.failure(object)
}
DispatchQueue.main.async {
self.delegate?.taskFinished(task: task)
}
self.runNextTask()
}
} else {
running = false
}
}
}
| gpl-3.0 | ca7726f9441d89a2c64a61dff255d7ce | 18.204918 | 108 | 0.594537 | 3.964467 | false | false | false | false |
Bauer312/ProjectEuler | Sources/Problem/Problem5.swift | 1 | 597 | import Multiples
public class Problem5 : Problem {
public var name: String
public var text: String
public var url: String
private(set) public var answer: String
public func solve() {
let mult = Multiples()
let multSet : [Int64] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
answer = String(mult.smallestMultiple(multSet))
}
public init () {
name = "Problem 5"
text = "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
url = "https://projecteuler.net/problem=5"
answer = "Not yet solved."
}
}
| mit | 0882cc932890122a3aaae2cfaf0259ff | 27.428571 | 110 | 0.664992 | 3.298343 | false | false | false | false |
mtviewdave/PhotoPicker | PhotoPicker/ImageEditor/ICImageEditViewController.swift | 1 | 24116 | //
// ICImageEditViewController.swift
// ImageEditor
//
// Created by Metebelis Labs LLC on 6/9/15.
//
// Copyright 2015 Metebelis Labs 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
protocol ICImageEditViewControllerDelegate {
func imageEditorDidEdit(sender : ICImageEditViewController,image : UIImage)
func imageEditorDidCancel(sender : ICImageEditViewController)
}
// Image editor
// Takes as input an image to edit
// Returns the edited image via a delegate callback
//
// The editor exists in two modes: an edit mode, where the user can rotate, scale
// and crop the image, and a display mode where the user can see the result of
// their editing. The editor starts in display mode.
class ICImageEditViewController: UIViewController,UIScrollViewDelegate,ICTouchDetectorViewDelegate {
var delegate : ICImageEditViewControllerDelegate?
@IBOutlet var scrollView : UIScrollView!;
var touchDetectorView = ICTouchDetectorView()
@IBOutlet var bottomContainerView : UIView!
@IBOutlet var cancelButton : UIButton!
@IBOutlet var useButton : UIButton!
@IBOutlet var doneButton : UIButton!
@IBOutlet var editButton : UIButton!
@IBOutlet var rotateButton : UIButton!
@IBOutlet var resetButton : UIButton!
var inEditMode = false
var imageView = UIImageView()
var minZoomScale = CGFloat(1)
let originalImage : UIImage // As received from the caller
var currentImage : UIImage // Rotated version of originalImage
var croppedImage : UIImage // Rotated and cropped
var croppedImageView = UIImageView()
var maxCropRectForScreen = CGRect()
var currentMaxCropRect = CGRect()
let margin = CGFloat(0)
let sideMargins = CGFloat(10)
let topMargin = CGFloat(10)
// In degrees because degrees are integer and thus
// it's easier to determine how much we've rotated
var currentRotationInDegrees = Int(0)
// Shown in edit mode
var cropBoxOverlay = ICCropBoxView(showInteriorLines: false)
// Has interior grid. Shown instead of cropBoxOverlay
// when user is adjusting crop box size
var cropBoxOverlayWithLines = ICCropBoxView(showInteriorLines: true)
var cropFrame = CGRect()
var sizerRatio = CGFloat(0)
let fadeTransitionTime = NSTimeInterval(0.1)
let moveTransitionTime = NSTimeInterval(0.2)
// Used to save old edit values for later restoration, so that a sequence like
// Edit -> (do edits) -> Done -> Edit -> (do more edits) -> Cancel
// works properly
var prevMinZoom = CGFloat(0)
var prevZoomScale = CGFloat(0)
var prevContentOffset = CGPointMake(0, 0)
var prevRotation : Int = 0
var prevCropFrame = CGRectMake(0, 0, 0, 0)
var prevMaxCropRect = CGRectMake(0, 0, 0, 0)
init(imageToEdit : UIImage) {
// Do this to strip out the orientation information from the image
UIGraphicsBeginImageContextWithOptions(imageToEdit.size, false, 1)
imageToEdit.drawAtPoint(CGPointMake(0, 0))
originalImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
currentImage = originalImage
croppedImage = currentImage
super.init(nibName: "ICImageEditViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoder not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(croppedImageView)
croppedImageView.hidden = true
let screenBounds = UIScreen.mainScreen().bounds
// This is the maximum theoretical rectangle the crop box can occupy
// The real maximum is the intersection of this with the bounds of the
// currently visible portion of the image
maxCropRectForScreen = CGRectMake(sideMargins, topMargin, screenBounds.width-2*sideMargins, screenBounds.height - bottomContainerView.frame.height-2*topMargin)
sizerRatio = maxCropRectForScreen.height/maxCropRectForScreen.width
scrollView.addSubview(imageView)
setup(firstTime:true)
self.cropBoxOverlay.alpha = 0
self.view.addSubview(cropBoxOverlay)
cropBoxOverlayWithLines.hidden = true
self.view.addSubview(cropBoxOverlayWithLines)
self.view.addSubview(touchDetectorView)
scrollView.scrollEnabled = false
return
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
touchDetectorView.frame = self.view.bounds
touchDetectorView.delegate = self
computeVisibleRect()
updateCropBox(currentMaxCropRect)
cropBoxOverlay.setNeedsDisplay()
cropBoxOverlayWithLines.setNeedsDisplay()
}
// Switching into and out of Edit mode
func switchToEditMode() {
if inEditMode {
return
}
inEditMode = true
// Store the old edits so we can restore them if the
// user taps "Cancel"
prevMinZoom = minZoomScale
prevZoomScale = scrollView.zoomScale
prevContentOffset = scrollView.contentOffset
prevRotation = currentRotationInDegrees
prevCropFrame = cropFrame
prevMaxCropRect = currentMaxCropRect
// Use changes
self.doneButton.hidden = false
self.rotateButton.hidden = false
self.resetButton.hidden = false
self.imageView.hidden = false
self.scrollView.hidden = false
self.scrollView.scrollEnabled = true
// This enables zooming
self.scrollView.minimumZoomScale = minZoomScale
self.scrollView.maximumZoomScale = 1.0
// Animate so that the cropped view slides into the spot
// it corresponds to in the whole image, so that it looks like
// the rest of the image is appearing
UIView.animateWithDuration(0.1, delay: 0, options: [.AllowUserInteraction, .CurveEaseInOut], animations: { () -> Void in
self.croppedImageView.frame = self.cropFrame
}) { (done) -> Void in
UIView.animateWithDuration(self.fadeTransitionTime, delay: 0, options: .AllowUserInteraction, animations: { () -> Void in
// Fade switch the UI elements
self.doneButton.alpha = 1
self.rotateButton.alpha = 1
self.resetButton.alpha = 1
self.useButton.alpha = 0
self.editButton.alpha = 0
self.cropBoxOverlay.alpha = 1
self.scrollView.alpha = 1
}) { (done) -> Void in
self.useButton.hidden = true
self.editButton.hidden = true
self.croppedImageView.hidden = true
}
}
}
func switchOutOfEditMode(animated : Bool) {
if !inEditMode {
return
}
inEditMode = false
// Compute the cropped image view frame
let croppedImageViewFrame = croppedImageView.frame
var centeredCroppedImageViewFrame = croppedImageViewFrame
centeredCroppedImageViewFrame.origin.x = maxCropRectForScreen.origin.x+(maxCropRectForScreen.size.width-croppedImageViewFrame.size.width)/2.0
centeredCroppedImageViewFrame.origin.y = maxCropRectForScreen.origin.y+(maxCropRectForScreen.size.height-croppedImageViewFrame.size.height)/2.0
self.useButton.hidden = false
self.editButton.hidden = false
self.croppedImageView.hidden = false
if !animated {
self.doneButton.alpha = 0
self.rotateButton.alpha = 0
self.resetButton.alpha = 0
self.useButton.alpha = 1
self.editButton.alpha = 1
self.cropBoxOverlay.alpha = 0
self.cropBoxOverlayWithLines.alpha = 0
self.scrollView.alpha = 0
self.doneButton.hidden = true
self.rotateButton.hidden = true
self.resetButton.hidden = true
self.imageView.hidden = true
self.scrollView.hidden = true
self.croppedImageView.frame = centeredCroppedImageViewFrame
return
}
UIView.animateWithDuration(fadeTransitionTime, delay: 0, options: .AllowUserInteraction, animations: { () -> Void in
self.doneButton.alpha = 0
self.rotateButton.alpha = 0
self.resetButton.alpha = 0
self.useButton.alpha = 1
self.editButton.alpha = 1
self.cropBoxOverlay.alpha = 0
self.cropBoxOverlayWithLines.alpha = 0
self.scrollView.alpha = 0
}) { (done) -> Void in
self.doneButton.hidden = true
self.rotateButton.hidden = true
self.resetButton.hidden = true
self.imageView.hidden = true
self.scrollView.hidden = true
UIView.animateWithDuration(self.moveTransitionTime, delay: 0, options: [.AllowUserInteraction, .CurveEaseInOut], animations: { () -> Void in
self.croppedImageView.frame = centeredCroppedImageViewFrame
}) { (done) -> Void in
}
}
}
// For debugging
func rectString(rect : CGRect) -> String {
return String(format: "(%g,%g,%g,%g)",arguments:[rect.origin.x,rect.origin.y,rect.size.width,rect.size.height])
}
// Update the crop box's frame, taking into account
// the box's margin (it has a margin to provide space for the
// "handles" on the corners of the box
func updateCropBox(frame : CGRect) {
cropFrame = frame
var cropBoxOverlayFrame = cropFrame
cropBoxOverlayFrame.origin.x -= ICCropBoxViewMargin
cropBoxOverlayFrame.origin.y -= ICCropBoxViewMargin
cropBoxOverlayFrame.size.width += 2*ICCropBoxViewMargin
cropBoxOverlayFrame.size.height += 2*ICCropBoxViewMargin
cropBoxOverlay.frame = cropBoxOverlayFrame
cropBoxOverlayWithLines.frame = cropBoxOverlayFrame
}
// When switching out of edit mode, this computes the "final"
// cropped, rotated image, stores it, and updates "croppedImageView" to
// display it
func updateCroppedImage() {
let frame = self.view.convertRect(cropFrame, toView: imageView)
if let imageRef = CGImageCreateWithImageInRect(currentImage.CGImage!, frame) {
croppedImage = UIImage(CGImage: imageRef)
croppedImageView.frame = cropFrame
croppedImageView.image = croppedImage
croppedImageView.hidden = false
}
}
// Compute the maximum practical bounds of the crop box
func computeVisibleRect() {
// Computes a rectangle that describes what portion of the scroll view is visible
var visibleRect = CGRect(origin: scrollView.contentOffset, size: scrollView.bounds.size)
let scale = 1.0 / scrollView.zoomScale
visibleRect.origin.x *= scale
visibleRect.origin.y *= scale
visibleRect.size.width *= scale
visibleRect.size.height *= scale
visibleRect.size.width = min(visibleRect.size.width,currentImage.size.width)
visibleRect.size.height = min(visibleRect.size.height,currentImage.size.height )
let imageViewInParent = imageView.convertRect(imageView.bounds, toView: self.view)
// Compute the intersection of the visible portion of the image with
// the maximum theoretical size of the crop box, which gives the actual
// maximum bounds of the crop box
currentMaxCropRect = CGRectIntersection(imageViewInParent, maxCropRectForScreen)
}
// Set up an image (either first time, or after a rotation)
// Sets up a new image view for the image, and sets up the
// scroll view to properly handle it
func setup(firstTime firstTime : Bool) {
var containerWidth = CGFloat(0)
var containerHeight = CGFloat(0)
if(maxCropRectForScreen.width/maxCropRectForScreen.height < currentImage.size.width / currentImage.size.height) {
containerWidth = currentImage.size.width*1.1
containerHeight = containerWidth*(maxCropRectForScreen.height/maxCropRectForScreen.width)
} else {
containerHeight = currentImage.size.height*1.1
containerWidth = containerHeight*(maxCropRectForScreen.width/maxCropRectForScreen.height)
}
imageView.removeFromSuperview()
imageView = UIImageView(frame: CGRectMake(0, 0, currentImage.size.width, currentImage.size.height))
imageView.image = currentImage
scrollView.addSubview(imageView)
let screenBounds = UIScreen.mainScreen().bounds
minZoomScale = min(screenBounds.width/containerWidth,screenBounds.height/containerHeight)
scrollView.contentInset = UIEdgeInsetsMake(
minZoomScale*(containerHeight-currentImage.size.height)/2.0,
minZoomScale*(containerWidth-currentImage.size.width)/2.0,
minZoomScale*(containerHeight-currentImage.size.height)/2.0 + bottomContainerView.bounds.height ,
minZoomScale*(containerWidth-currentImage.size.width)/2.0
)
let newZoomScale = minZoomScale
// Set up the zoom scale and disable zooming until the user enters edit mode
scrollView.minimumZoomScale = newZoomScale
scrollView.maximumZoomScale = newZoomScale
scrollView.zoomScale = newZoomScale
}
//
// Rotation handling
//
func rotateImage(origImage : UIImage,rotationInRadians : CGFloat) -> UIImage {
let origSize = originalImage.size
// Used to compute the original image's frame should look like after we apply
// a rotation transform
// Not as clean as pure math, but easier to maintain and understand
let sizerBox = UIView(frame: CGRectMake(0, 0, originalImage.size.width, originalImage.size.height))
sizerBox.transform = CGAffineTransformMakeRotation(rotationInRadians)
let rotatedSize = sizerBox.frame.size
UIGraphicsBeginImageContextWithOptions(rotatedSize, false , 1)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context!, rotatedSize.width/2, rotatedSize.height/2)
CGContextRotateCTM(context!, rotationInRadians)
CGContextScaleCTM(context!, 1.0, -1.0)
CGContextDrawImage(context!, CGRectMake(-origSize.width/2, -origSize.height/2, origSize.width, origSize.height), originalImage.CGImage!)
let result = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return result
}
func deg2rad(degrees : Int) -> CGFloat {
return CGFloat(degrees) * CGFloat(M_PI / 180.0)
}
func makeCurrentImageFromRotatingOriginalImage(degrees : Int) {
self.currentImage = self.rotateImage(self.originalImage, rotationInRadians: self.deg2rad(degrees))
self.setup(firstTime:false)
self.scrollView.minimumZoomScale = minZoomScale
self.scrollView.maximumZoomScale = 1
updateCropBox(currentMaxCropRect)
cropBoxOverlay.setNeedsDisplay()
cropBoxOverlayWithLines.setNeedsDisplay()
}
//
// Touch handling
//
var lastLocation = CGPoint()
var movingLeftEdge = false
var movingRightEdge = false
var movingTopEdge = false
var movingBottomEdge = false
let touchZoneMargins = CGFloat(15)
func touchBegan(sender : ICTouchDetectorView,pointInDetectorView: CGPoint) {
let point = sender.convertPoint(pointInDetectorView, toView: self.view)
self.cropBoxOverlayWithLines.hidden = false
// When the crop box is being moved, we hide cropBoxOverlay and show cropBoxOverlayWithLines
// (in a nice animated fashion) so that the lines appear to appear
UIView.animateWithDuration(0.1, delay: 0, options: .AllowUserInteraction, animations: { () -> Void in
self.cropBoxOverlayWithLines.alpha = 1
}) { (done) -> Void in
if done {
self.cropBoxOverlay.hidden = true
}
}
var innerTouchZone = cropFrame
innerTouchZone.origin.x += touchZoneMargins
innerTouchZone.origin.y += touchZoneMargins
innerTouchZone.size.width -= touchZoneMargins*2
innerTouchZone.size.height -= touchZoneMargins*2
// Note that we can be moving one edge, or we can
// be moving a side and top/bottom edge simultaneously
if point.x < innerTouchZone.origin.x {
movingLeftEdge = true
} else if point.x > innerTouchZone.origin.x + innerTouchZone.size.width {
movingRightEdge = true
}
if point.y < innerTouchZone.origin.y {
movingTopEdge = true
} else if point.y > innerTouchZone.origin.y + innerTouchZone.size.height {
movingBottomEdge = true
}
lastLocation = point
}
func touchMoved(sender : ICTouchDetectorView,pointInDetectorView: CGPoint) {
let point = sender.convertPoint(pointInDetectorView, toView: self.view)
adjustCropBox(point)
}
func touchEnded(sender : ICTouchDetectorView,pointInDetectorView: CGPoint) {
movingTopEdge = false
movingBottomEdge = false
movingLeftEdge = false
movingRightEdge = false
confineCropBox()
self.cropBoxOverlay.hidden = false
// Replace cropBoxOverlayWithLines with cropBoxOverlay
UIView.animateWithDuration(0.1, delay: 0, options: .AllowUserInteraction, animations: { () -> Void in
self.cropBoxOverlayWithLines.alpha = 0
}) { (done) -> Void in
if done {
self.cropBoxOverlayWithLines.hidden = true
}
}
}
func shouldHandleTouch(sender : ICTouchDetectorView,pointInDetectorView: CGPoint) -> Bool {
// We handle a touch if we're in edit mode, and if the touch appears on
// the edge of the current crop box (+/- touchZoneMargins)
let point = sender.convertPoint(pointInDetectorView, toView: self.view)
if !inEditMode {
return false
}
// Compute two rectangles:
// CropBox + touchZoneMargins
// CropBox - touchZoneMargins
// If we're within the first and outside of the second, we're
// on the border of the crop box and should thus handle touch events
var outerTouchZone = cropFrame
outerTouchZone.origin.x -= touchZoneMargins
outerTouchZone.origin.y -= touchZoneMargins
outerTouchZone.size.width += touchZoneMargins*2
outerTouchZone.size.height += touchZoneMargins*2
if !CGRectContainsPoint(outerTouchZone, point) {
return false
}
var innerTouchZone = cropFrame
innerTouchZone.origin.x += touchZoneMargins
innerTouchZone.origin.y += touchZoneMargins
innerTouchZone.size.width -= touchZoneMargins*2
innerTouchZone.size.height -= touchZoneMargins*2
if CGRectContainsPoint(innerTouchZone, point) {
return false
}
return true
}
// Adjust the size of the crop box to match the delta between
// the user's last touch event and the current touch event positions
func adjustCropBox(point : CGPoint) {
let minCropBoxDimension = CGFloat(60)
let deltaX = point.x - lastLocation.x
let deltaY = point.y - lastLocation.y
var frame = cropFrame
if movingTopEdge {
frame.origin.y += deltaY
frame.size.height -= deltaY
} else if movingBottomEdge {
frame.size.height += deltaY
}
if movingLeftEdge {
frame.origin.x += deltaX
frame.size.width -= deltaX
} else if movingRightEdge {
frame.size.width += deltaX
}
if frame.size.width < minCropBoxDimension || frame.size.height < minCropBoxDimension {
return
}
updateCropBox(frame)
cropBoxOverlay.setNeedsDisplay()
cropBoxOverlayWithLines.setNeedsDisplay()
lastLocation = point
}
// If the crop box is outside the current bounds of the image,
// shrink it to fit
func confineCropBox() {
UIView.animateWithDuration(0.15, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.updateCropBox(CGRectIntersection(self.cropFrame, self.currentMaxCropRect))
}, completion: {(done) -> Void in
self.cropBoxOverlay.setNeedsDisplay()
})
}
// Required UIScrollViewDelegate stuff
func scrollViewDidZoom(scrollView: UIScrollView) {
computeVisibleRect()
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidScroll(scrollView: UIScrollView) {
computeVisibleRect()
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
confineCropBox()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
confineCropBox()
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
confineCropBox()
}
// Actions
@IBAction func doneTapped() {
updateCroppedImage()
switchOutOfEditMode(true)
}
@IBAction func useTapped() {
if let delegate = delegate {
delegate.imageEditorDidEdit(self, image: croppedImage)
}
}
@IBAction func cancelTapped() {
if inEditMode {
// Switch to non-Edit mode
makeCurrentImageFromRotatingOriginalImage(prevRotation)
currentRotationInDegrees = prevRotation
scrollView.minimumZoomScale = prevMinZoom
updateCropBox(prevCropFrame)
currentMaxCropRect = prevMaxCropRect
scrollView.zoomScale = prevZoomScale
scrollView.contentOffset = prevContentOffset
updateCroppedImage()
switchOutOfEditMode(false)
} else {
// We're done
if let delegate = delegate {
delegate.imageEditorDidCancel(self)
}
}
}
@IBAction func resetTapped() {
currentRotationInDegrees = 0
makeCurrentImageFromRotatingOriginalImage(0)
}
@IBAction func editTapped() {
switchToEditMode()
}
@IBAction func rotateTapped() {
currentRotationInDegrees -= 90
if currentRotationInDegrees < 0 {
currentRotationInDegrees += 360
}
makeCurrentImageFromRotatingOriginalImage(currentRotationInDegrees)
}
}
| apache-2.0 | 89ee287a744218114f210ad24ac26a5d | 36.977953 | 167 | 0.642146 | 4.999171 | false | false | false | false |
bravelocation/daysleft | daysleft/Model Extensions/AppSettings+DayCalculations.swift | 1 | 2393 | //
// AppSettings+DayCalculations.swift
// DaysLeft
//
// Created by John Pollard on 20/09/2022.
// Copyright © 2022 Brave Location Software. All rights reserved.
//
import Foundation
extension AppSettings {
/// Property to get the number of days between the start and the end
var daysLength: Int {
return Date.daysDifference(self.start, endDate: self.end, weekdaysOnly: self.weekdaysOnly) + 1 // Inclusive so add one
}
/// Finds the number of days to the end of the period from the current date
///
/// - Parameter currentDate: The current date
/// - Returns: The number of days to the end from the current date
func daysLeft(_ currentDate: Date) -> Int {
let startCurrentDate = currentDate.startOfDay
// If the current date is before the start, return the length
let startComparison = startCurrentDate.compare(self.start)
if startComparison == ComparisonResult.orderedAscending {
return self.daysLength
}
// If the current date is after the end, return 0
if startCurrentDate.compare(self.end) == ComparisonResult.orderedDescending {
return 0
}
// Otherwise, return the actual difference
return self.daysLength - self.daysGone(startCurrentDate)
}
/// Finds the number of days from the start of the period from the current date
///
/// - Parameter currentDate: The current date
/// - Returns: The number of days from the start to the current date
func daysGone(_ currentDate: Date) -> Int {
let startCurrentDate = currentDate.startOfDay
let startComparison = startCurrentDate.compare(self.start)
// If the current date is before the start (not weekdays only), return 0
if startComparison == ComparisonResult.orderedAscending && self.weekdaysOnly == false {
return 0
}
// If the current date is after the end, return the length
if startCurrentDate.compare(self.end) == ComparisonResult.orderedDescending {
return self.daysLength
}
// Otherwise, return the actual difference
return Date.daysDifference(self.start, endDate: currentDate, currentDate: currentDate, weekdaysOnly: self.weekdaysOnly) + 1 // Inclusive so add 1
}
}
| mit | 03a460a0c5c76723526b0a202514732e | 36.968254 | 153 | 0.651338 | 4.952381 | false | false | false | false |
kdbertel/NoMockSwift | NoMockSwift/NoMockSwift/Person.swift | 1 | 343 | public struct Person {
public let name: String
init(name: String) {
self.name = name
}
}
extension Person : Equatable {}
public func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name
}
extension Person : Printable {
public var description: String {
return "[\(name)]"
}
}
| unlicense | 7a7d99d9d36c37e67067dc5cfd29e9a8 | 15.333333 | 50 | 0.580175 | 3.988372 | false | false | false | false |
alessioarsuffi/AASheetController | AASheetController/Classes/AASheetController.swift | 1 | 11284 | //
// RSAlertController.swift
// RSAlertController
//
// Created by Alessio Arsuffi on 07/12/2016.
// Copyright © 2016 Alessio Arsuffi. All rights reserved.
//
import UIKit
import Photos
/// AASheetControllerDelegate
public protocol AASheetControllerDelegate: class {
/// This method return an UIImage when user tap sheetController's collectionView
///
/// - Parameter image: UIImage from sheetController
func sheetController(didSelect image: UIImage)
}
/// AASheetController
public class AASheetController: UIViewController {
// MARK: Properties
/// This is the size of the image that you want back in AASheetControllerDelegate
/// - note: default CGSize.zero
public var imageSize = CGSize.zero
/// Define the collectionView cell size
/// - note: default CGSize(width: 100, height: 100)
public let cellSize = CGSize(width: 100, height: 100)
/// Whether a cancel button should be visible at the bottom of the actionSheet
/// - note: default = true
public var showCancelButton: Bool = true {
didSet {
shouldShowCancelButton()
}
}
/// This define the delegate
public weak var delegate: AASheetControllerDelegate?
/// Whether system photoLibrary should be visible at the top of the actionSheet
/// - note: default = true
public var showCollectionView: Bool = true {
didSet {
shouldShowCollectionView()
}
}
/// Change this value to edit action view height
public var alertStackViewHeight : CGFloat = 57
var separator = UIImageView()
var fetchResult: PHFetchResult<PHAsset>! {
didSet {
collectionView.reloadData()
imageManager = PHCachingImageManager()
}
}
var imageManager: PHCachingImageManager? = nil
// MARK: IBOutlets
@IBOutlet weak var alertMaskBackground: UIImageView!
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var upperView: UIView! {
didSet {
upperView.layer.cornerRadius = 13
}
}
@IBOutlet weak var alertActionStackView: UIStackView!
@IBOutlet weak var cancelButtonView: UIView! {
didSet {
cancelButtonView.layer.cornerRadius = 13
}
}
@IBOutlet weak var alertStackViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
let cellNib = UINib.init(nibName: "AACollectionViewCell", bundle: Bundle(for: self.classForCoder))
collectionView.register(cellNib, forCellWithReuseIdentifier: AACollectionViewCell.identifier)
}
}
@IBOutlet weak var alertViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var alertTitle: UILabel!
@IBOutlet weak var alertDescription: UILabel!
@IBOutlet weak var headerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var alertImage: UIImageView!
// MARK: View lifecycle
/// viewWillAppear
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
animateAppearing()
shouldShowCollectionView()
}
/// viewWillDisappear
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
animateDisappearing()
}
//MARK: - Initialiser
@objc public convenience init(barButtonItem: UIBarButtonItem?) {
self.init()
let nib = loadNibAlertController()
if nib != nil{
self.view = nib![0] as! UIView
}
modalPresentationStyle = .overCurrentContext
modalTransitionStyle = .crossDissolve
if UIDevice.current.userInterfaceIdiom == .pad, barButtonItem != nil {
modalPresentationStyle = .popover
popoverPresentationController?.barButtonItem = barButtonItem
}
shouldShowCancelButton()
dismissOnTapOutside()
}
// MARK: - Separator
fileprivate func addSeparator() {
separator.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
alertActionStackView.addSubview(separator)
// Autolayout separator
separator.translatesAutoresizingMaskIntoConstraints = false
separator.topAnchor.constraint(equalTo: alertActionStackView.topAnchor).isActive = true
separator.centerXAnchor.constraint(equalTo: alertActionStackView.centerXAnchor).isActive = true
separator.heightAnchor.constraint(equalTo: alertActionStackView.heightAnchor).isActive = true
separator.widthAnchor.constraint(equalToConstant: 1).isActive = true
}
//MARK: - Actions
/// Add an AASheetAction to sheetController,
/// - note: To change height use alertStackViewHeight
@objc public func addAction(_ alertAction: AASheetAction) {
alertActionStackView.addArrangedSubview(alertAction)
alertActionStackView.axis = .vertical
alertStackViewHeightConstraint.constant = alertStackViewHeight * CGFloat(alertActionStackView.arrangedSubviews.count)
alertAction.addTarget(self, action: #selector(AASheetController.dismissAlertController(_:)), for: .touchUpInside)
}
fileprivate func addCancelAction() {
let cancelAction = AASheetAction(title: "Cancel", style: .cancel)
cancelButtonView.addSubview(cancelAction)
cancelAction.translatesAutoresizingMaskIntoConstraints = false
cancelAction.widthAnchor.constraint(equalTo: cancelButtonView.widthAnchor).isActive = true
cancelAction.heightAnchor.constraint(equalTo: cancelButtonView.heightAnchor).isActive = true
cancelAction.centerXAnchor.constraint(equalTo: cancelButtonView.centerXAnchor).isActive = true
cancelAction.topAnchor.constraint(equalTo: cancelButtonView.topAnchor).isActive = true
cancelAction.addTarget(self, action: #selector(AASheetController.dismissAlertController(_:)), for: .touchUpInside)
}
@objc fileprivate func dismissAlertController(_ sender: AASheetAction) {
self.dismiss(animated: true, completion: nil)
}
fileprivate func dismissOnTapOutside() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AASheetController.dismissAlertController(_:)))
tapGesture.numberOfTouchesRequired = 1
tapGesture.numberOfTapsRequired = 1
alertMaskBackground.addGestureRecognizer(tapGesture)
alertMaskBackground.isUserInteractionEnabled = true
}
//MARK: - Customizations
fileprivate func shouldShowCancelButton() {
if showCancelButton {
cancelButtonView.isHidden = false
addCancelAction()
} else {
cancelButtonView.subviews.forEach({ $0.removeFromSuperview() })
cancelButtonView.isHidden = true
}
}
fileprivate func shouldShowCollectionView() {
if showCollectionView {
fetchAllPhotos()
} else {
collectionView.isHidden = true
}
}
@objc fileprivate func loadNibAlertController() -> [AnyObject]? {
let podBundle = Bundle(for: self.classForCoder)
if let bundleURL = podBundle.url(forResource: "AASheetController", withExtension: "bundle"){
if let bundle = Bundle(url: bundleURL) {
return bundle.loadNibNamed("AASheetController", owner: self, options: nil) as [AnyObject]?
}
else {
assertionFailure("Could not load the bundle")
}
}
else if let nib = podBundle.loadNibNamed("AASheetController", owner: self, options: nil) as [AnyObject]? {
return nib
}
else{
assertionFailure("Could not create a path to the bundle")
}
return nil
}
//MARK: - Animations
fileprivate func animateAppearing() {
alertMaskBackground.backgroundColor = UIColor.black.withAlphaComponent(0.00)
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseInOut, animations: {
var alertViewFrame = self.alertView.frame
alertViewFrame.origin.y -= self.view.frame.size.height
self.alertView.frame = alertViewFrame
self.alertMaskBackground.backgroundColor = self.modalPresentationStyle == .overCurrentContext ? UIColor.black.withAlphaComponent(0.40) : .clear
}, completion: { (finished: Bool) in
})
}
fileprivate func animateDisappearing() {
alertMaskBackground.backgroundColor = modalPresentationStyle == .overCurrentContext ? UIColor.black.withAlphaComponent(0.40) : .clear
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
var alertViewFrame = self.alertView.frame
alertViewFrame.origin.y += self.view.frame.size.height
self.alertView.frame = alertViewFrame
self.alertMaskBackground.backgroundColor = UIColor.black.withAlphaComponent(0.00)
}, completion: { (finished: Bool) in
})
}
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate,
extension AASheetController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
///
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchResult == nil ? 0 : fetchResult.count
}
///
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AACollectionViewCell.identifier, for: indexPath) as! AACollectionViewCell
let asset = fetchResult.object(at: indexPath.item)
cell.representedAssetIdentifier = asset.localIdentifier
imageManager?.requestImage(for: asset, targetSize: cellSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
if cell.representedAssetIdentifier == asset.localIdentifier {
cell.imageView.image = image
}
})
return cell
}
///
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
///
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let asset = fetchResult.object(at: indexPath.item)
imageManager?.requestImage(for: asset, targetSize: targetSize(), contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
self.delegate?.sheetController(didSelect: image!)
self.dismiss(animated: true, completion: nil)
})
}
}
| mit | d26ea520ddf709dd2bc93379d04debd8 | 35.993443 | 167 | 0.664008 | 5.689864 | false | false | false | false |
sahandnayebaziz/Dana-Hills | Dana Hills/ArticleViewController.swift | 1 | 1848 | //
// ArticleViewController.swift
// Dana Hills
//
// Created by Nayebaziz, Sahand on 9/21/16.
// Copyright © 2016 Nayebaziz, Sahand. All rights reserved.
//
import UIKit
class ArticleViewController: UIViewController {
let article: NewsArticle
init(withArticle article: NewsArticle) {
self.article = article
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
title = article.title
automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor.white
let textView = UITextView()
textView.isEditable = false
textView.text = String(htmlEncodedString: article.body)
textView.font = UIFont.preferredFont(forTextStyle: .body)
view.addSubview(textView)
textView.snp.makeConstraints { make in
make.top.equalTo(topLayoutGuide.snp.bottom).offset(12)
make.bottom.equalTo(bottomLayoutGuide.snp.top)
make.width.equalTo(view).offset(-24)
make.centerX.equalTo(view)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension String {
init(htmlEncodedString: String) {
self.init()
guard let encodedData = htmlEncodedString.data(using: .utf8) else {
self = htmlEncodedString
return
}
do {
let attributedString = try NSAttributedString(data: encodedData, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil)
self = attributedString.string
} catch {
print("Error: \(error)")
self = htmlEncodedString
}
}
}
| mit | 171a3957022707af952dd7108eb24eb7 | 28.790323 | 217 | 0.628587 | 4.797403 | false | false | false | false |
cc001/learnSwiftBySmallProjects | 10-SpotifyVideoBackground/SpotifyVideoBackground/VideoSplashViewController.swift | 1 | 3390 | //
// VideoSplashViewController.swift
// SpotifyVideoBackground
//
// Created by 陈闯 on 2016/12/20.
// Copyright © 2016年 CC. All rights reserved.
//
import UIKit
import MediaPlayer
import AVKit
public enum ScalingMode {
case resize
case resizeAspect
case resizeAspectFill
}
open class VideoSplashViewController: UIViewController {
fileprivate let moviePlayer = AVPlayerViewController()
fileprivate var moviePlayerSoundLevel: Float = 1.0
open var contentURL: URL? {
didSet {
setMoviePlayer(contentURL!)
}
}
open var videoFrame: CGRect = CGRect()
open var startTime: CGFloat = 0.0
open var duration: CGFloat = 0.0
open var backgroundColor: UIColor = UIColor.black {
didSet {
view.backgroundColor = backgroundColor
}
}
open var sound: Bool = true {
didSet {
if sound {
moviePlayerSoundLevel = 1.0
}else{
moviePlayerSoundLevel = 0.0
}
}
}
open var alpha: CGFloat = CGFloat() {
didSet {
moviePlayer.view.alpha = alpha
}
}
open var alwaysRepeat: Bool = true {
didSet {
if alwaysRepeat {
NotificationCenter.default.addObserver(self,
selector: #selector(VideoSplashViewController.playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: moviePlayer.player?.currentItem)
}
}
}
open var fillMode: ScalingMode = .resizeAspectFill {
didSet {
switch fillMode {
case .resize:
moviePlayer.videoGravity = AVLayerVideoGravityResize
case .resizeAspect:
moviePlayer.videoGravity = AVLayerVideoGravityResizeAspect
case .resizeAspectFill:
moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill
}
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
moviePlayer.view.frame = videoFrame
moviePlayer.showsPlaybackControls = false
view.addSubview(moviePlayer.view)
view.sendSubview(toBack: moviePlayer.view)
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
fileprivate func setMoviePlayer(_ url: URL){
let videoCutter = VideoCutter()
videoCutter.cropVideoWithUrl(videoUrl: url, startTime: startTime, duration: duration) { (videoPath, error) -> Void in
if let path = videoPath as URL? {
self.moviePlayer.player = AVPlayer(url: path)
self.moviePlayer.player?.play()
self.moviePlayer.player?.volume = self.moviePlayerSoundLevel
}
}
}
override open func viewDidLoad() {
super.viewDidLoad()
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func playerItemDidReachEnd() {
moviePlayer.player?.seek(to: kCMTimeZero)
moviePlayer.player?.play()
}
}
| mit | 2e7b9b613ce1713158dc038aa35e1a20 | 29.477477 | 125 | 0.590009 | 5.70489 | false | false | false | false |
guoc/spi | SPiKeyboard/TastyImitationKeyboard/ExtraView.swift | 1 | 937 | //
// ExtraView.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 10/5/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
class ExtraView: UIView {
var globalColors: GlobalColors.Type?
var darkMode: Bool {
didSet {
if oldValue != darkMode {
updateAppearance()
}
}
}
var solidColorMode: Bool
required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) {
self.globalColors = globalColors
self.darkMode = darkMode
self.solidColorMode = solidColorMode
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
self.globalColors = nil
self.darkMode = false
self.solidColorMode = false
super.init(coder: aDecoder)
}
func updateAppearance() {
}
}
| bsd-3-clause | 176fb2b36166d2196ff3544b5e71ede6 | 21.309524 | 91 | 0.588047 | 4.805128 | false | false | false | false |
xedin/swift | stdlib/public/Darwin/Foundation/DateInterval.swift | 5 | 8748 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
/// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct DateInterval : ReferenceConvertible, Comparable, Hashable, Codable {
public typealias ReferenceType = NSDateInterval
/// The start date.
public var start : Date
/// The end date.
///
/// - precondition: `end >= start`
public var end : Date {
get {
return start + duration
}
set {
precondition(newValue >= start, "Reverse intervals are not allowed")
duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
}
/// The duration.
///
/// - precondition: `duration >= 0`
public var duration : TimeInterval {
willSet {
precondition(newValue >= 0, "Negative durations are not allowed")
}
}
/// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`.
public init() {
let d = Date()
start = d
duration = 0
}
/// Initialize a `DateInterval` with the specified start and end date.
///
/// - precondition: `end >= start`
public init(start: Date, end: Date) {
if end < start {
fatalError("Reverse intervals are not allowed")
}
self.start = start
duration = end.timeIntervalSince(start)
}
/// Initialize a `DateInterval` with the specified start date and duration.
///
/// - precondition: `duration >= 0`
public init(start: Date, duration: TimeInterval) {
precondition(duration >= 0, "Negative durations are not allowed")
self.start = start
self.duration = duration
}
/**
Compare two DateIntervals.
This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g. Given intervals a and b
```
a. |-----|
b. |-----|
```
`a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g. Given intervals c and d
```
c. |-----|
d. |---|
```
`c.compare(d)` would result in `.OrderedDescending` because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result.
*/
public func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = start.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
/// Returns `true` if `self` intersects the `dateInterval`.
public func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end)
}
/// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect.
///
/// In the event that there is no intersection, the method returns nil.
public func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if self == dateInterval {
return self
}
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = start
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = end
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
/// Returns `true` if `self` contains `date`.
public func contains(_ date: Date) -> Bool {
let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalforSelfEnd = end.timeIntervalSinceReferenceDate
if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) {
return true
}
return false
}
public func hash(into hasher: inout Hasher) {
hasher.combine(start)
hasher.combine(duration)
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static func ==(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.start == rhs.start && lhs.duration == rhs.duration
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public static func <(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension DateInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(start) to \(end)"
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "start", value: start))
c.append((label: "end", value: end))
c.append((label: "duration", value: duration))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension DateInterval : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSDateInterval.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateInterval {
return NSDateInterval(start: start, duration: duration)
}
public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) {
if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool {
result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval {
var result: DateInterval?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSDateInterval : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as DateInterval)
}
}
| apache-2.0 | aef48519d5503df7d2d9c731334b442f | 36.87013 | 327 | 0.638432 | 5.148911 | false | false | false | false |
hamin/EventSource.Swift | EventSourceSwiftDemo/lib/SwiftEventSource.swift | 1 | 9115 | //
// SwiftEventSource.swift
// SwiftEvenSourceDemo
//
// Created by Haris Amin on 1/21/15.
// Copyright (c) 2015 Haris Amin. All rights reserved.
//
import Foundation
let ESKeyValueDelimiter = ": "
let ESEventSeparatorLFLF = "\n\n"
let ESEventSeparatorCRCR = "\r\r"
let ESEventSeparatorCRLFCRLF = "\r\n\r\n"
let ESEventKeyValuePairSeparator = "\n"
let ESEventDataKey = "data"
let ESEventIDKey = "id"
let ESEventEventKey = "event"
let ESEventRetryKey = "retry"
// MARK: EventState
enum EventState : CustomStringConvertible {
case CONNECTING;
case OPEN;
case CLOSED;
var description : String {
switch self {
case .CONNECTING: return "CONNECTING";
case .OPEN: return "OPEN";
case .CLOSED: return "CLOSED";
}
}
}
// MARK: EventType
enum EventType : CustomStringConvertible {
case MESSAGE;
case ERROR;
case OPEN;
var description : String {
switch self {
case .MESSAGE: return "MESSAGE";
case .ERROR: return "ERROR";
case .OPEN: return "OPEN";
}
}
}
class Event: NSObject{
var eventId:String? = nil
var event:String? = nil
var data:String? = nil
var error:NSError? = nil
var readyState:EventState = EventState.CLOSED
}
typealias EventSourceHandler = (Event) -> Void
@objc protocol EventSourceDelegate{
optional func eventSourceOpenedConnection(event:Event)
optional func eventSourceReceivedError(event:Event, error:NSError)
optional func eventSourceReceivedMessage(event:Event, message: String)
}
class EventSource: NSObject, NSURLSessionDataDelegate {
private var eventURL:NSURL?
private var eventSourceTask:NSURLSessionDataTask?
private var listeners = Dictionary<String, [EventSourceHandler]>()
private var timeoutInterval:NSTimeInterval = 300.0
private var retryInterval:NSTimeInterval = 1.0
private var lastEventID:String?
private var wasClosed:Bool = true
weak var delegate:EventSourceDelegate?
init(url:String) {
self.eventURL = NSURL(string: url)
super.init()
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(self.retryInterval * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
self.open()
}
}
func open(){
self.wasClosed = false
let request = NSMutableURLRequest(URL: self.eventURL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: self.timeoutInterval)
if(self.lastEventID != nil){
request.setValue(self.lastEventID, forHTTPHeaderField: "Last-Event-ID")
}
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var additionalHeaders: [NSObject : AnyObject] = ["Accept":"text/event-stream", "Cache-Control": "no-cache"]
if(self.lastEventID != nil){
additionalHeaders["Last-Event-ID"] = self.lastEventID
}
configuration.HTTPAdditionalHeaders = additionalHeaders
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue())
self.eventSourceTask = session.dataTaskWithRequest(request)
self.eventSourceTask?.resume()
}
func close(){
self.wasClosed = true
self.eventSourceTask?.cancel()
}
func addEventListener(eventName:String, handler:EventSourceHandler){
if(self.listeners[eventName] == nil){
self.listeners[eventName] = []
}
self.listeners[eventName]!.append(handler)
}
func onMessage(handler:EventSourceHandler){
self.addEventListener(EventType.MESSAGE.description, handler: handler)
}
func onError(handler:EventSourceHandler){
self.addEventListener(EventType.ERROR.description, handler: handler)
}
func onOpen(handler:EventSourceHandler){
self.addEventListener(EventType.OPEN.description, handler: handler)
}
// MARK: NSURLSessionDataDelegate
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
var eventString = NSString(data: data, encoding: NSUTF8StringEncoding)
if( eventString!.hasSuffix(ESEventSeparatorLFLF) ||
eventString!.hasSuffix(ESEventSeparatorCRCR) ||
eventString!.hasSuffix(ESEventSeparatorCRLFCRLF) ) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
eventString = eventString!.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
let components = eventString!.componentsSeparatedByString(ESEventKeyValuePairSeparator)
let event = Event()
event.readyState = EventState.OPEN
for component in components{
if(component.characters.count == 0){
continue
}
let range = component.rangeOfString(ESKeyValueDelimiter)
let index: Int = component.startIndex.distanceTo(range!.startIndex)
if (index == NSNotFound || index == (component.characters.count - 2)) {
continue;
}
let keyIndex = component.startIndex.advancedBy(index)
let key = component.substringToIndex(keyIndex)
let countForKeyValueDelimimter = ESKeyValueDelimiter.characters.count
let valueIndex = component.startIndex.advancedBy(index + countForKeyValueDelimimter)
let value = component.substringToIndex(valueIndex)
if ( key == ESEventIDKey) {
event.eventId = value;
self.lastEventID = event.eventId;
} else if (key == ESEventEventKey) {
event.event = value;
} else if (key == ESEventDataKey) {
event.data = value;
} else if (key == ESEventRetryKey) {
self.retryInterval = (value as NSString).doubleValue
}
}
self.delegate?.eventSourceReceivedMessage?(event, message: eventString! as String)
if let messageHandlers:[EventSourceHandler] = self.listeners[EventType.MESSAGE.description]{
for handler in messageHandlers{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(event)
})
}
}
if(event.event != nil){
if let namedEventhandlers:[EventSourceHandler] = self.listeners[event.event!]{
for handler in namedEventhandlers{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(event)
})
}
}
}
})
}
}
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
completionHandler(NSURLSessionResponseDisposition.Allow)
let httpResponse = response as! NSHTTPURLResponse
if(httpResponse.statusCode == 200){
// Opened
let event = Event()
event.readyState = EventState.OPEN
self.delegate?.eventSourceOpenedConnection?(event)
if let openHandlers:[EventSourceHandler] = self.listeners[EventType.OPEN.description]{
for handler in openHandlers{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(event)
})
}
}
}
}
internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
print("THERE IS AN ERROR: \(error)")
let event = Event()
event.readyState = EventState.CLOSED
event.error = error
self.delegate?.eventSourceReceivedError?(event, error: error!)
if let errorHandlers:[EventSourceHandler] = self.listeners[EventType.ERROR.description]{
for handler in errorHandlers{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
handler(event)
})
}
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(self.retryInterval * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
self.open()
}
}
}
} | mit | d2c4b413f403de522f6b3eb296755e90 | 35.464 | 193 | 0.604498 | 5.120787 | false | false | false | false |
fxdemolisher/newscats | ios/NewsCats/EnvironmentManager.swift | 1 | 2773 | import Freddy
import UIKit
/**
* Utility for initializing the application's environment.
*/
struct EnvironmentManager {
/**
* Describes the application's environment.
*/
struct Environment {
// Generic flags.
let name: String
let installationId: String
// RN specific flags.
let localBundleInDebug: Bool
let allowDebugActions: Bool
// Application information.
let bundleId: String
let version: String
let build: String
let buildMachineIp: String
}
/**
* Returns an instance of Environment for the current build config.
*/
static func initWithName(name: String) -> Environment {
// Basic info.
let mainBundle = Bundle.main
let version = mainBundle.infoDictionary?["CFBundleShortVersionString"] as! String
let build = mainBundle.infoDictionary?[kCFBundleVersionKey as String] as! String
// Installation id.
var installationId = UserDefaults.standard.string(forKey: "installationId")
if (installationId == nil) {
installationId = UUID.init().uuidString
UserDefaults.standard.set(installationId, forKey: "installationId")
}
// Local bundle or dev server (if in dev mode).
var localBundleInDebug = false
if let candidate = UserDefaults.standard.bool(forKey: "localBundleInDebug") as Bool? {
localBundleInDebug = candidate
}
// Build machine IP retrieval.
let path = Bundle.main.path(forResource: "BuildEnvironment-Info", ofType: "plist")!
let infoDict = NSDictionary(contentsOfFile: path) as! [String : Any]
let buildMachineIp = infoDict["BUILD_MACHINE_IP"] as! String
return Environment(
name: name,
installationId: installationId!,
localBundleInDebug: localBundleInDebug,
allowDebugActions: ("debug" == name),
bundleId: mainBundle.bundleIdentifier!,
version: version,
build: build,
buildMachineIp: buildMachineIp
)
}
}
/**
* JSON serialization support for environment instances.
*/
extension EnvironmentManager.Environment : JSONEncodable {
func toJSON() -> JSON {
return .dictionary([
"name": .string(name),
"installationId": .string(installationId),
"localBundleInDebug": .bool(localBundleInDebug),
"allowDebugActions": .bool(allowDebugActions),
"bundleId": .string(bundleId),
"version": .string(version),
"build": .string(build),
"buildMachineIp": .string(buildMachineIp),
])
}
}
| apache-2.0 | 21bb9443eb371c6bbff10119e80a8304 | 32.409639 | 94 | 0.608006 | 5.097426 | false | false | false | false |
Punch-In/PunchInIOSApp | PunchIn/MKButton.swift | 1 | 4005 | //
// MKButton.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
@IBDesignable
public class MKButton : UIButton
{
@IBInspectable public var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable public var ripplePercent: Float = 0.9 {
didSet {
mkLayer.ripplePercent = ripplePercent
}
}
@IBInspectable public var backgroundLayerCornerRadius: CGFloat = 0.0 {
didSet {
mkLayer.setBackgroundLayerCornerRadius(backgroundLayerCornerRadius)
}
}
// animations
@IBInspectable public var shadowAniEnabled: Bool = true
@IBInspectable public var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable public var rippleAniDuration: Float = 0.75
@IBInspectable public var backgroundAniDuration: Float = 1.0
@IBInspectable public var shadowAniDuration: Float = 0.65
@IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var shadowAniTimingFunction: MKTimingFunction = .EaseOut
@IBInspectable public var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(rippleLayerColor)
}
}
@IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override public var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
// MARK - initilization
override public init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setupLayer()
}
// MARK - setup methods
private func setupLayer() {
adjustsImageWhenHighlighted = false
cornerRadius = 2.5
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setCircleLayerColor(rippleLayerColor)
}
// MARK - location tracking methods
override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
if rippleLocation == .TapLocation {
mkLayer.didChangeTapLocation(touch.locationInView(self))
}
// rippleLayer animation
mkLayer.animateScaleForCircleLayer(0.45, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration))
// backgroundLayer animation
if backgroundAniEnabled {
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration))
}
// shadow animation for self
if shadowAniEnabled {
let shadowRadius = layer.shadowRadius
let shadowOpacity = layer.shadowOpacity
let duration = CFTimeInterval(shadowAniDuration)
mkLayer.animateSuperLayerShadow(10, toRadius: shadowRadius, fromOpacity: 0, toOpacity: shadowOpacity, timingFunction: shadowAniTimingFunction, duration: duration)
}
return super.beginTrackingWithTouch(touch, withEvent: event)
}
}
| mit | ce88b411f44af1ea9508f86bdb748a88 | 32.655462 | 174 | 0.666167 | 5.368633 | false | false | false | false |
lukejmann/FBLA2017 | Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView.swift | 1 | 16054 | //
// NVActivityIndicatorView.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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
/**
Enum of animation types used for activity indicator view.
- Blank: Blank animation.
- BallPulse: BallPulse animation.
- BallGridPulse: BallGridPulse animation.
- BallClipRotate: BallClipRotate animation.
- SquareSpin: SquareSpin animation.
- BallClipRotatePulse: BallClipRotatePulse animation.
- BallClipRotateMultiple: BallClipRotateMultiple animation.
- BallPulseRise: BallPulseRise animation.
- BallRotate: BallRotate animation.
- CubeTransition: CubeTransition animation.
- BallZigZag: BallZigZag animation.
- BallZigZagDeflect: BallZigZagDeflect animation.
- BallTrianglePath: BallTrianglePath animation.
- BallScale: BallScale animation.
- LineScale: LineScale animation.
- LineScaleParty: LineScaleParty animation.
- BallScaleMultiple: BallScaleMultiple animation.
- BallPulseSync: BallPulseSync animation.
- BallBeat: BallBeat animation.
- LineScalePulseOut: LineScalePulseOut animation.
- LineScalePulseOutRapid: LineScalePulseOutRapid animation.
- BallScaleRipple: BallScaleRipple animation.
- BallScaleRippleMultiple: BallScaleRippleMultiple animation.
- BallSpinFadeLoader: BallSpinFadeLoader animation.
- LineSpinFadeLoader: LineSpinFadeLoader animation.
- TriangleSkewSpin: TriangleSkewSpin animation.
- Pacman: Pacman animation.
- BallGridBeat: BallGridBeat animation.
- SemiCircleSpin: SemiCircleSpin animation.
- BallRotateChase: BallRotateChase animation.
- Orbit: Orbit animation.
- AudioEqualizer: AudioEqualizer animation.
*/
public enum NVActivityIndicatorType: Int {
/**
Blank.
- returns: Instance of NVActivityIndicatorAnimationBlank.
*/
case blank
/**
BallPulse.
- returns: Instance of NVActivityIndicatorAnimationBallPulse.
*/
case ballPulse
/**
BallGridPulse.
- returns: Instance of NVActivityIndicatorAnimationBallGridPulse.
*/
case ballGridPulse
/**
BallClipRotate.
- returns: Instance of NVActivityIndicatorAnimationBallClipRotate.
*/
case ballClipRotate
/**
SquareSpin.
- returns: Instance of NVActivityIndicatorAnimationSquareSpin.
*/
case squareSpin
/**
BallClipRotatePulse.
- returns: Instance of NVActivityIndicatorAnimationBallClipRotatePulse.
*/
case ballClipRotatePulse
/**
BallClipRotateMultiple.
- returns: Instance of NVActivityIndicatorAnimationBallClipRotateMultiple.
*/
case ballClipRotateMultiple
/**
BallPulseRise.
- returns: Instance of NVActivityIndicatorAnimationBallPulseRise.
*/
case ballPulseRise
/**
BallRotate.
- returns: Instance of NVActivityIndicatorAnimationBallRotate.
*/
case ballRotate
/**
CubeTransition.
- returns: Instance of NVActivityIndicatorAnimationCubeTransition.
*/
case cubeTransition
/**
BallZigZag.
- returns: Instance of NVActivityIndicatorAnimationBallZigZag.
*/
case ballZigZag
/**
BallZigZagDeflect
- returns: Instance of NVActivityIndicatorAnimationBallZigZagDeflect
*/
case ballZigZagDeflect
/**
BallTrianglePath.
- returns: Instance of NVActivityIndicatorAnimationBallTrianglePath.
*/
case ballTrianglePath
/**
BallScale.
- returns: Instance of NVActivityIndicatorAnimationBallScale.
*/
case ballScale
/**
LineScale.
- returns: Instance of NVActivityIndicatorAnimationLineScale.
*/
case lineScale
/**
LineScaleParty.
- returns: Instance of NVActivityIndicatorAnimationLineScaleParty.
*/
case lineScaleParty
/**
BallScaleMultiple.
- returns: Instance of NVActivityIndicatorAnimationBallScaleMultiple.
*/
case ballScaleMultiple
/**
BallPulseSync.
- returns: Instance of NVActivityIndicatorAnimationBallPulseSync.
*/
case ballPulseSync
/**
BallBeat.
- returns: Instance of NVActivityIndicatorAnimationBallBeat.
*/
case ballBeat
/**
LineScalePulseOut.
- returns: Instance of NVActivityIndicatorAnimationLineScalePulseOut.
*/
case lineScalePulseOut
/**
LineScalePulseOutRapid.
- returns: Instance of NVActivityIndicatorAnimationLineScalePulseOutRapid.
*/
case lineScalePulseOutRapid
/**
BallScaleRipple.
- returns: Instance of NVActivityIndicatorAnimationBallScaleRipple.
*/
case ballScaleRipple
/**
BallScaleRippleMultiple.
- returns: Instance of NVActivityIndicatorAnimationBallScaleRippleMultiple.
*/
case ballScaleRippleMultiple
/**
BallSpinFadeLoader.
- returns: Instance of NVActivityIndicatorAnimationBallSpinFadeLoader.
*/
case ballSpinFadeLoader
/**
LineSpinFadeLoader.
- returns: Instance of NVActivityIndicatorAnimationLineSpinFadeLoader.
*/
case lineSpinFadeLoader
/**
TriangleSkewSpin.
- returns: Instance of NVActivityIndicatorAnimationTriangleSkewSpin.
*/
case triangleSkewSpin
/**
Pacman.
- returns: Instance of NVActivityIndicatorAnimationPacman.
*/
case pacman
/**
BallGridBeat.
- returns: Instance of NVActivityIndicatorAnimationBallGridBeat.
*/
case ballGridBeat
/**
SemiCircleSpin.
- returns: Instance of NVActivityIndicatorAnimationSemiCircleSpin.
*/
case semiCircleSpin
/**
BallRotateChase.
- returns: Instance of NVActivityIndicatorAnimationBallRotateChase.
*/
case ballRotateChase
/**
Orbit.
- returns: Instance of NVActivityIndicatorAnimationOrbit.
*/
case orbit
/**
AudioEqualizer.
- returns: Instance of NVActivityIndicatorAnimationAudioEqualizer.
*/
case audioEqualizer
static let allTypes = (blank.rawValue ... audioEqualizer.rawValue).map { NVActivityIndicatorType(rawValue: $0)! }
func animation() -> NVActivityIndicatorAnimationDelegate {
switch self {
case .blank:
return NVActivityIndicatorAnimationBlank()
case .ballPulse:
return NVActivityIndicatorAnimationBallPulse()
case .ballGridPulse:
return NVActivityIndicatorAnimationBallGridPulse()
case .ballClipRotate:
return NVActivityIndicatorAnimationBallClipRotate()
case .squareSpin:
return NVActivityIndicatorAnimationSquareSpin()
case .ballClipRotatePulse:
return NVActivityIndicatorAnimationBallClipRotatePulse()
case .ballClipRotateMultiple:
return NVActivityIndicatorAnimationBallClipRotateMultiple()
case .ballPulseRise:
return NVActivityIndicatorAnimationBallPulseRise()
case .ballRotate:
return NVActivityIndicatorAnimationBallRotate()
case .cubeTransition:
return NVActivityIndicatorAnimationCubeTransition()
case .ballZigZag:
return NVActivityIndicatorAnimationBallZigZag()
case .ballZigZagDeflect:
return NVActivityIndicatorAnimationBallZigZagDeflect()
case .ballTrianglePath:
return NVActivityIndicatorAnimationBallTrianglePath()
case .ballScale:
return NVActivityIndicatorAnimationBallScale()
case .lineScale:
return NVActivityIndicatorAnimationLineScale()
case .lineScaleParty:
return NVActivityIndicatorAnimationLineScaleParty()
case .ballScaleMultiple:
return NVActivityIndicatorAnimationBallScaleMultiple()
case .ballPulseSync:
return NVActivityIndicatorAnimationBallPulseSync()
case .ballBeat:
return NVActivityIndicatorAnimationBallBeat()
case .lineScalePulseOut:
return NVActivityIndicatorAnimationLineScalePulseOut()
case .lineScalePulseOutRapid:
return NVActivityIndicatorAnimationLineScalePulseOutRapid()
case .ballScaleRipple:
return NVActivityIndicatorAnimationBallScaleRipple()
case .ballScaleRippleMultiple:
return NVActivityIndicatorAnimationBallScaleRippleMultiple()
case .ballSpinFadeLoader:
return NVActivityIndicatorAnimationBallSpinFadeLoader()
case .lineSpinFadeLoader:
return NVActivityIndicatorAnimationLineSpinFadeLoader()
case .triangleSkewSpin:
return NVActivityIndicatorAnimationTriangleSkewSpin()
case .pacman:
return NVActivityIndicatorAnimationPacman()
case .ballGridBeat:
return NVActivityIndicatorAnimationBallGridBeat()
case .semiCircleSpin:
return NVActivityIndicatorAnimationSemiCircleSpin()
case .ballRotateChase:
return NVActivityIndicatorAnimationBallRotateChase()
case .orbit:
return NVActivityIndicatorAnimationOrbit()
case .audioEqualizer:
return NVActivityIndicatorAnimationAudioEqualizer()
}
}
}
/// Activity indicator view with nice animations
public final class NVActivityIndicatorView: UIView {
/// Default type. Default value is .BallSpinFadeLoader.
public static var DEFAULT_TYPE: NVActivityIndicatorType = .ballSpinFadeLoader
/// Default color of activity indicator. Default value is UIColor.white.
public static var DEFAULT_COLOR = UIColor.white
/// Default color of text. Default value is UIColor.white.
public static var DEFAULT_TEXT_COLOR = UIColor.white
/// Default padding. Default value is 0.
public static var DEFAULT_PADDING: CGFloat = 0
/// Default size of activity indicator view in UI blocker. Default value is 60x60.
public static var DEFAULT_BLOCKER_SIZE = CGSize(width: 60, height: 60)
/// Default display time threshold to actually display UI blocker. Default value is 0 ms.
public static var DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD = 0
/// Default minimum display time of UI blocker. Default value is 0 ms.
public static var DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME = 0
/// Default message displayed in UI blocker. Default value is nil.
public static var DEFAULT_BLOCKER_MESSAGE: String?
/// Default font of message displayed in UI blocker. Default value is bold system font, size 20.
public static var DEFAULT_BLOCKER_MESSAGE_FONT = UIFont.boldSystemFont(ofSize: 20)
/// Default background color of UI blocker. Default value is UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
public static var DEFAULT_BLOCKER_BACKGROUND_COLOR = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
/// Animation type.
public var type: NVActivityIndicatorType = NVActivityIndicatorView.DEFAULT_TYPE
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'type' instead.")
@IBInspectable var typeName: String {
get {
return getTypeName()
}
set {
_setTypeName(newValue)
}
}
/// Color of activity indicator view.
@IBInspectable public var color: UIColor = NVActivityIndicatorView.DEFAULT_COLOR
/// Padding of activity indicator view.
@IBInspectable public var padding: CGFloat = NVActivityIndicatorView.DEFAULT_PADDING
/// Current status of animation, read-only.
@available(*, deprecated: 3.1)
public var animating: Bool { return isAnimating }
/// Current status of animation, read-only.
private(set) public var isAnimating: Bool = false
/**
Returns an object initialized from data in a given unarchiver.
self, initialized using the data in decoder.
- parameter decoder: an unarchiver object.
- returns: self, initialized using the data in decoder.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clear
isHidden = true
}
/**
Create a activity indicator view.
Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params.
- parameter frame: view's frame.
- parameter type: animation type.
- parameter color: color of activity indicator view.
- parameter padding: padding of activity indicator view.
- returns: The activity indicator view.
*/
public init(frame: CGRect, type: NVActivityIndicatorType? = nil, color: UIColor? = nil, padding: CGFloat? = nil) {
self.type = type ?? NVActivityIndicatorView.DEFAULT_TYPE
self.color = color ?? NVActivityIndicatorView.DEFAULT_COLOR
self.padding = padding ?? NVActivityIndicatorView.DEFAULT_PADDING
super.init(frame: frame)
isHidden = true
}
// Fix issue #62
// Intrinsic content size is used in autolayout
// that causes mislayout when using with MBProgressHUD.
/**
Returns the natural size for the receiving view, considering only properties of the view itself.
A size indicating the natural size for the receiving view based on its intrinsic properties.
- returns: A size indicating the natural size for the receiving view based on its intrinsic properties.
*/
public override var intrinsicContentSize: CGSize {
return CGSize(width: bounds.width, height: bounds.height)
}
/**
Start animating.
*/
public final func startAnimating() {
isHidden = false
isAnimating = true
layer.speed = 1
setUpAnimation()
}
/**
Stop animating.
*/
public final func stopAnimating() {
isHidden = true
isAnimating = false
layer.sublayers?.removeAll()
}
// MARK: Internal
func _setTypeName(_ typeName: String) {
for item in NVActivityIndicatorType.allTypes {
if String(describing: item).caseInsensitiveCompare(typeName) == ComparisonResult.orderedSame {
type = item
break
}
}
}
func getTypeName() -> String {
return String(describing: type)
}
// MARK: Privates
private final func setUpAnimation() {
let animation: NVActivityIndicatorAnimationDelegate = type.animation()
var animationRect = UIEdgeInsetsInsetRect(frame, UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding))
let minEdge = min(animationRect.width, animationRect.height)
layer.sublayers = nil
animationRect.size = CGSize(width: minEdge, height: minEdge)
animation.setUpAnimation(in: layer, size: animationRect.size, color: color)
}
}
| mit | f67d4d84baebf5550e1e37cffcec3e85 | 32.238095 | 132 | 0.689174 | 5.518735 | false | false | false | false |
SunLiner/Floral | Floral/Floral/Classes/Profile/Profile/Controller/ProfileTableViewController.swift | 1 | 1696 | //
// ProfileViewController.swift
// Floral
//
// Created by ALin on 16/4/25.
// Copyright © 2016年 ALin. All rights reserved.
// 暂时没有上
import UIKit
// 作者简介的cell重用标识符
private let UserCellReuseIdentifier = "UserCollectionCell"
class ProfileViewController: ColumnistViewController {
override func setup() {
super.setup()
collectionView?.registerClass(UserCollectionViewCell.self, forCellWithReuseIdentifier: UserCellReuseIdentifier)
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(UserCellReuseIdentifier, forIndexPath: indexPath) as! UserCollectionViewCell
cell.author = author
return cell
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ArticlesreuseIdentifier, forIndexPath: indexPath) as! ArticlesCollectionViewCell
let count = articles?.count ?? 0
if count > 0 {
cell.article = articles![indexPath.item]
}
return cell
}
// MAKR: - UICollectionViewDelegateFlowLayout
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
if indexPath.section == 0 {
return CGSizeMake(UIScreen.mainScreen().bounds.width
, 160);
}else{
return CGSizeMake((UIScreen.mainScreen().bounds.width - 24)/2, 230);
}
}
}
| mit | 06149ab58ad5d6683d543c3a058a6323 | 36.795455 | 176 | 0.692123 | 5.599327 | false | false | false | false |
yuwang17/WYExtensionUtil | WYExtensionUtil/WYExtensionString.swift | 1 | 2297 | //
// WYExtensionString.swift
// WYUtil
//
// Created by Wang Yu on 11/9/15.
// Copyright © 2015 Wang Yu. All rights reserved.
//
import UIKit
extension String {
var count: Int { return self.characters.count }
func length() -> Int {
return self.characters.count
}
subscript(idx: Int) -> Character {
return self[self.startIndex.advancedBy(idx)]
}
func toURL() -> NSURL? {
return NSURL(string: self)
}
func addToPasteboard() {
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = self
}
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
func testRegularExpression(pattern:String) ->Bool {
let expression: NSRegularExpression?
do {
expression = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
} catch _ as NSError {
expression = nil
}
let matches = expression?.numberOfMatchesInString(self, options: [], range: NSMakeRange(0, self.characters.count))
return matches > 0
}
func stringToInt() -> Int {
if let i = Int(self) {
return i
} else {
return 0
}
}
func fromHtmlToAttributedString() -> NSAttributedString! {
let htmlData = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let htmlString: NSAttributedString?
do {
htmlString = try NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch _ {
htmlString = nil
}
return htmlString
}
}
public func randomStringWithLength (len : Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for _ in 0 ..< len {
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return randomString as String
}
| mit | dc351f6e0c897c4f9f481ad98f95aea3 | 27.345679 | 157 | 0.623693 | 5.147982 | false | false | false | false |
natecook1000/swift | test/SILOptimizer/definite_init_failable_initializers.swift | 1 | 71440 | // RUN: %target-swift-frontend -emit-sil -enable-sil-ownership %s | %FileCheck %s
// High-level tests that DI handles early returns from failable and throwing
// initializers properly. The main complication is conditional release of self
// and stored properties.
// FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases
// are fully covered, though.
////
// Structs with failable initializers
////
protocol Pachyderm {
init()
}
class Canary : Pachyderm {
required init() {}
}
// <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer
struct TrivialFailableStruct {
init?(blah: ()) { }
init?(wibble: ()) {
self.init(blah: wibble)
}
}
struct FailableStruct {
let x, y: Canary
init(noFail: ()) {
x = Canary()
y = Canary()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[SELF]]
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers14FailableStructV30failAfterPartialInitializationACSgyt_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY]] to [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[SELF]]
init?(failAfterPartialInitialization: ()) {
x = Canary()
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers14FailableStructV27failAfterFullInitializationACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY1:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK: [[CANARY2:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
x = Canary()
y = Canary()
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByAssignmentACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[SELF_VALUE]]
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableStruct(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByDelegationACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14FailableStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers14FailableStructV20failDuringDelegationACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: br [[FAIL_EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: retain_value [[SELF_VALUE]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>)
//
// CHECK: [[FAIL_EPILOG_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableStruct>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableStruct>)
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
init!(failDuringDelegation3: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation4: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation5: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableStruct {
init?(failInExtension: ()) {
self.init(failInExtension: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableStruct(noFail: ())
}
}
struct FailableAddrOnlyStruct<T : Pachyderm> {
var x, y: T
init(noFail: ()) {
x = T()
y = T()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failBeforeInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: return
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterPartialInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: return
init?(failAfterPartialInitialization: ()) {
x = T()
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterFullInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[Y_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: return
init?(failAfterFullInitialization: ()) {
x = T()
y = T()
return nil
}
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableAddrOnlyStruct(noFail: ())
return nil
}
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation3: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation4: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableAddrOnlyStruct {
init?(failInExtension: ()) {
self.init(failBeforeInitialization: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableAddrOnlyStruct(noFail: ())
}
}
////
// Structs with throwing initializers
////
func unwrap(_ x: Int) throws -> Int { return x }
struct ThrowStruct {
var x: Canary
init(fail: ()) throws { x = Canary() }
init(noFail: ()) { x = Canary() }
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV28failBeforeOrDuringDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV29failBeforeOrDuringDelegation2ACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV19failAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV27failDuringOrAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb7, bb6
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV27failBeforeOrAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb7, bb6
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV16throwsToOptionalACSgSi_tcfC
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG1]], [[ARG2]]) : $@convention(method) (Int, @thin ThrowStruct.Type) -> (@owned ThrowStruct, @error Error), normal [[TRY_APPLY_SUCC_BB:bb[0-9]+]], error [[TRY_APPLY_FAIL_BB:bb[0-9]+]]
//
// CHECK: [[TRY_APPLY_SUCC_BB]]([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]]
// CHECK-NEXT: br [[TRY_APPLY_CONT:bb[0-9]+]]([[SELF_OPTIONAL]] : $Optional<ThrowStruct>)
//
// CHECK: [[TRY_APPLY_CONT]]([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>):
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: br [[FAIL_EPILOG_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: retain_value [[SELF_VALUE]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[FAIL_EPILOG_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<ThrowStruct>):
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct>
//
// CHECK: [[TRY_APPLY_FAIL_TRAMPOLINE_BB:bb[0-9]+]]:
// CHECK-NEXT: strong_release [[ERROR:%.*]] : $Error
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[TRY_APPLY_CONT]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[TRY_APPLY_FAIL_BB]]([[ERROR]] : $Error):
// CHECK-NEXT: br [[TRY_APPLY_FAIL_TRAMPOLINE_BB]]
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsToOptionalThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowStruct(noFail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV25failDuringSelfReplacementACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
// CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringSelfReplacement: Int) throws {
try self = ThrowStruct(fail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers11ThrowStructV24failAfterSelfReplacementACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
// CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterSelfReplacement: Int) throws {
self = ThrowStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
try self = ThrowStruct(fail: ())
}
}
struct ThrowAddrOnlyStruct<T : Pachyderm> {
var x : T
init(fail: ()) throws { x = T() }
init(noFail: ()) { x = T() }
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsOptionalToThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowAddrOnlyStruct(noFail: ())
}
init(failAfterSelfReplacement: Int) throws {
self = ThrowAddrOnlyStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowAddrOnlyStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
self = ThrowAddrOnlyStruct(noFail: ())
}
}
////
// Classes with failable initializers
////
class FailableBaseClass {
var member: Canary
init(noFail: ()) {
member = Canary()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type
// CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]]
// CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK: return [[RESULT]]
init?(failBeforeFullInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17FailableBaseClassC27failAfterFullInitializationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Canary
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
member = Canary()
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17FailableBaseClassC20failBeforeDelegationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick FailableBaseClass.Type, %0 : $FailableBaseClass
// CHECK-NEXT: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] : $@thick FailableBaseClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[RESULT]]
convenience init?(failBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[RESULT]]
convenience init?(failAfterDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK: release_value [[SELF_OPTIONAL]]
// CHECK: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[SELF_VALUE]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableBaseClass>)
//
// CHECK: [[FAIL_TRAMPOLINE_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableBaseClass>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>):
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
convenience init?(failDuringDelegation: ()) {
self.init(failBeforeFullInitialization: ())
}
// IUO to optional
convenience init!(failDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
convenience init!(noFailDuringDelegation: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
convenience init(noFailDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // necessary '!'
}
}
extension FailableBaseClass {
convenience init?(failInExtension: ()) throws {
self.init(failBeforeFullInitialization: failInExtension)
}
}
// Chaining to failable initializers in a superclass
class FailableDerivedClass : FailableBaseClass {
var otherMember: Canary
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %0 : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[RESULT]]
init?(derivedFailBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Canary
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[SELF_VALUE]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableDerivedClass>)
//
// CHECK: [[FAIL_TRAMPOLINE_BB]]:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableDerivedClass>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>):
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass>
init?(derivedFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failBeforeFullInitialization: ())
}
init?(derivedFailAfterDelegation: ()) {
self.otherMember = Canary()
super.init(noFail: ())
return nil
}
// non-optional to IUO
init(derivedNoFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // necessary '!'
}
// IUO to IUO
init!(derivedFailDuringDelegation2: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!'
}
}
extension FailableDerivedClass {
convenience init?(derivedFailInExtension: ()) throws {
self.init(derivedFailDuringDelegation: derivedFailInExtension)
}
}
////
// Classes with throwing initializers
////
class ThrowBaseClass {
required init() throws {}
init(noFail: ()) {}
}
class ThrowDerivedClass : ThrowBaseClass {
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK: bb0(%0 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
required init() throws {
try super.init()
}
override init(noFail: ()) {
try! super.init()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitializationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK0ACSi_SitKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int)
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %2 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitializationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int) throws {
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitialization0h6DuringjK0ACSi_SitKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws {
try super.init()
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h5AfterjK0ACSi_SitKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[TWO:%.*]] = integer_literal $Builtin.Int2, -2
// CHECK-NEXT: store [[TWO]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]]
// CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%1)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) : $Builtin.Int1
// CHECK-NEXT: cond_br [[COND]], bb6, bb10
// CHECK: bb6:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[SHIFTED:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) : $Builtin.Int2
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[SHIFTED]] : $Builtin.Int2) : $Builtin.Int1
// CHECK-NEXT: cond_br [[COND]], bb7, bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb9
// CHECK: bb8:
// CHECK-NEXT: br bb9
// CHECK: bb9:
// CHECK-NEXT: br bb11
// CHECK: bb10:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb11
// CHECK: bb11:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK00h5AfterjK0ACSi_S2itKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %3 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %3
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]]
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[NEG_ONE:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[NEG_ONE]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%2)
// CHECK: bb3([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb8, bb12
// CHECK: bb8:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb9, bb10
// CHECK: bb9:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb11
// CHECK: bb10:
// CHECK-NEXT: br bb11
// CHECK: bb11:
// CHECK-NEXT: br bb13
// CHECK: bb12:
// CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb13
// CHECK: bb13:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
try unwrap(failAfterFullInitialization)
}
convenience init(noFail2: ()) {
try! self.init()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC20failDuringDelegationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
convenience init(failDuringDelegation: Int) throws {
try self.init()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeOrDuringDelegationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int1
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init()
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC29failBeforeOrDuringDelegation2ACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int1
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: store %1 to [[SELF_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb5([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[RELOADED_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[RELOADED_SELF]] : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref [[RELOADED_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR2]]
convenience init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC19failAfterDelegationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC27failDuringOrAfterDelegationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failDuringOrAfterDelegation: Int) throws {
try self.init()
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @$S35definite_init_failable_initializers17ThrowDerivedClassC27failBeforeOrAfterDelegationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -2
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$S35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$S35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) : $Builtin.Int1
// CHECK-NEXT: cond_br [[COND]], bb6, bb10
// CHECK: bb6:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb7, bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb9
// CHECK: bb8:
// CHECK-NEXT: br bb9
// CHECK: bb9:
// CHECK-NEXT: br bb11
// CHECK: bb10:
// CHECK-NEXT: [[OLD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[OLD_SELF]] : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref [[OLD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb11
// CHECK: bb11:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
}
////
// Enums with failable initializers
////
enum FailableEnum {
case A
init?(a: Int64) { self = .A }
init!(b: Int64) {
self.init(a: b)! // unnecessary-but-correct '!'
}
init(c: Int64) {
self.init(a: c)! // necessary '!'
}
init(d: Int64) {
self.init(b: d)! // unnecessary-but-correct '!'
}
}
////
// Protocols and protocol extensions
////
// Delegating to failable initializers from a protocol extension to a
// protocol.
protocol P1 {
init?(p1: Int64)
}
extension P1 {
init!(p1a: Int64) {
self.init(p1: p1a)! // unnecessary-but-correct '!'
}
init(p1b: Int64) {
self.init(p1: p1b)! // necessary '!'
}
}
protocol P2 : class {
init?(p2: Int64)
}
extension P2 {
init!(p2a: Int64) {
self.init(p2: p2a)! // unnecessary-but-correct '!'
}
init(p2b: Int64) {
self.init(p2: p2b)! // necessary '!'
}
}
// Delegating to failable initializers from a protocol extension to a
// protocol extension.
extension P1 {
init?(p1c: Int64) {
self.init(p1: p1c)
}
init!(p1d: Int64) {
self.init(p1c: p1d)! // unnecessary-but-correct '!'
}
init(p1e: Int64) {
self.init(p1c: p1e)! // necessary '!'
}
}
extension P2 {
init?(p2c: Int64) {
self.init(p2: p2c)
}
init!(p2d: Int64) {
self.init(p2c: p2d)! // unnecessary-but-correct '!'
}
init(p2e: Int64) {
self.init(p2c: p2e)! // necessary '!'
}
}
////
// type(of: self) with uninitialized self
////
func use(_ a : Any) {}
class DynamicTypeBase {
var x: Int
init() {
use(type(of: self))
x = 0
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
class DynamicTypeDerived : DynamicTypeBase {
override init() {
use(type(of: self))
super.init()
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
struct DynamicTypeStruct {
var x: Int
init() {
use(type(of: self))
x = 0
}
init(a : Int) {
use(type(of: self))
self.init()
}
}
| apache-2.0 | b5b908611c0f535f80caca7dca29703e | 41.906907 | 227 | 0.617819 | 3.230387 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/EStickItem.swift | 1 | 3276 | //
// EStickItem.swift
// Telegram-Mac
//
// Created by keepcoder on 17/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
class EStickItem: TableRowItem {
override var height: CGFloat {
return 30
}
override var stableId: AnyHashable {
return _stableId
}
private let _stableId: AnyHashable
let layout:(TextNodeLayout, TextNode)
fileprivate let clearCallback:(()->Void)?
init(_ initialSize:NSSize, stableId: AnyHashable, segmentName:String, clearCallback:(()->Void)? = nil) {
self._stableId = stableId
self.clearCallback = clearCallback
layout = TextNode.layoutText(maybeNode: nil, .initialize(string: segmentName.uppercased(), color: theme.colors.grayText, font: .medium(.short)), nil, 1, .end, NSMakeSize(.greatestFiniteMagnitude, .greatestFiniteMagnitude), nil, false, .left)
super.init(initialSize)
}
override func viewClass() -> AnyClass {
return EStickView.self
}
}
private class EStickView: TableStickView {
private var button: ImageButton?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
layerContentsRedrawPolicy = .onSetNeedsDisplay
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var backdorColor: NSColor {
return .clear
}
override func layout() {
super.layout()
if let view = self.button {
view.centerY(x: frame.width - view.frame.width - 20)
}
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item, animated: animated)
guard let item = item as? EStickItem else {
return
}
if let callback = item.clearCallback {
let current: ImageButton
if let view = self.button {
current = view
} else {
current = ImageButton()
current.autohighlight = false
current.scaleOnClick = true
current.set(image: theme.icons.wallpaper_color_close, for: .Normal)
current.sizeToFit()
addSubview(current)
self.button = current
}
current.removeAllHandlers()
current.set(handler: { _ in
callback()
}, for: .Click)
} else if let view = self.button {
performSubviewRemoval(view, animated: animated)
self.button = nil
}
needsDisplay = true
needsLayout = true
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
if header {
ctx.setFillColor(theme.colors.border.cgColor)
ctx.fill(NSMakeRect(0, frame.height - .borderSize, frame.width, .borderSize))
}
if let item = item as? EStickItem {
var f = focus(item.layout.0.size)
f.origin.x = 20
f.origin.y -= 1
item.layout.1.draw(f, in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: backdorColor)
}
}
}
| gpl-2.0 | 1e63286ed145c097da8918b0419d92d8 | 29.324074 | 250 | 0.579237 | 4.599719 | false | false | false | false |
blumareks/iot-watson-swift | lab3/ios/WatsonIoTCreate2/Carthage/Checkouts/bms-clientsdk-swift-core/Source/Security/Identity/BaseDeviceIdentity.swift | 7 | 5358 | /*
* Copyright 2015 IBM Corp.
* 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 WatchKit
// MARK: - Swift 3
#if swift(>=3.0)
// This class represents the base device identity class, with default methods and keys
open class BaseDeviceIdentity: DeviceIdentity {
public struct Key {
public static let ID = "id"
public static let OS = "platform"
public static let OSVersion = "osVersion"
public static let model = "model"
}
public internal(set) var jsonData: [String:String] = ([:])
public private(set) var extendedJsonData : [String:Any] = [String:Any]()
public var ID: String? {
get {
return jsonData[BaseDeviceIdentity.Key.ID] != nil ? jsonData[BaseDeviceIdentity.Key.ID] : (extendedJsonData[BaseDeviceIdentity.Key.ID] as? String)
}
}
public var OS: String? {
get {
return jsonData[BaseDeviceIdentity.Key.OS] != nil ? jsonData[BaseDeviceIdentity.Key.OS] : (extendedJsonData[BaseDeviceIdentity.Key.OS] as? String)
}
}
public var OSVersion: String? {
get {
return jsonData[BaseDeviceIdentity.Key.OSVersion] != nil ? jsonData[BaseDeviceIdentity.Key.OSVersion] : (extendedJsonData[BaseDeviceIdentity.Key.OSVersion] as? String)
}
}
public var model: String? {
get {
return jsonData[BaseDeviceIdentity.Key.model] != nil ? jsonData[BaseDeviceIdentity.Key.model] : (extendedJsonData[BaseDeviceIdentity.Key.model] as? String)
}
}
public init() {
#if os(watchOS)
jsonData[BaseDeviceIdentity.Key.ID] = "Not Available"
jsonData[BaseDeviceIdentity.Key.OS] = WKInterfaceDevice.current().systemName
jsonData[BaseDeviceIdentity.Key.OSVersion] = WKInterfaceDevice.current().systemVersion
jsonData[BaseDeviceIdentity.Key.model] = WKInterfaceDevice.current().model
#else
jsonData[BaseDeviceIdentity.Key.ID] = UIDevice.current.identifierForVendor?.uuidString
jsonData[BaseDeviceIdentity.Key.OS] = UIDevice.current.systemName
jsonData[BaseDeviceIdentity.Key.OSVersion] = UIDevice.current.systemVersion
jsonData[BaseDeviceIdentity.Key.model] = UIDevice.current.model
#endif
}
public convenience init(map: [String:AnyObject]?) {
self.init(map : map as [String:Any]?)
}
public init(map: [String:Any]?) {
extendedJsonData = map != nil ? map! : [String:Any]()
guard let json = map as? [String:String] else {
jsonData = ([:])
return
}
jsonData = json
}
}
/**************************************************************************************************/
// MARK: - Swift 2
#else
// This class represents the base device identity class, with default methods and keys
public class BaseDeviceIdentity: DeviceIdentity {
public struct Key {
public static let ID = "id"
public static let OS = "platform"
public static let OSVersion = "osVersion"
public static let model = "model"
}
public internal(set) var jsonData: [String:String] = ([:])
public var ID: String? {
get {
return jsonData[BaseDeviceIdentity.Key.ID]
}
}
public var OS: String? {
get {
return jsonData[BaseDeviceIdentity.Key.OS]
}
}
public var OSVersion: String? {
get {
return jsonData[BaseDeviceIdentity.Key.OSVersion]
}
}
public var model: String? {
get {
return jsonData[BaseDeviceIdentity.Key.model]
}
}
public init() {
#if os(watchOS)
jsonData[BaseDeviceIdentity.Key.ID] = "Not Available"
jsonData[BaseDeviceIdentity.Key.OS] = WKInterfaceDevice.currentDevice().systemName
jsonData[BaseDeviceIdentity.Key.OSVersion] = WKInterfaceDevice.currentDevice().systemVersion
jsonData[BaseDeviceIdentity.Key.model] = WKInterfaceDevice.currentDevice().model
#else
jsonData[BaseDeviceIdentity.Key.ID] = UIDevice.currentDevice().identifierForVendor?.UUIDString
jsonData[BaseDeviceIdentity.Key.OS] = UIDevice.currentDevice().systemName
jsonData[BaseDeviceIdentity.Key.OSVersion] = UIDevice.currentDevice().systemVersion
jsonData[BaseDeviceIdentity.Key.model] = UIDevice.currentDevice().model
#endif
}
public init(map: [String:AnyObject]?) {
guard let json = map as? [String:String] else {
jsonData = ([:])
return
}
jsonData = json
}
}
#endif
| gpl-3.0 | 577e149896f243350fc17ad2b7cc1155 | 27.956522 | 170 | 0.615803 | 4.534468 | false | false | false | false |
Elethom/PRSlideView | Sources/PRSlideView.swift | 2 | 23969 | //
// PRSlideView.swift
// PRSlideView
//
// Created by Elethom Hunter on 7/11/19.
// Copyright © 2019 Wiredcraft. All rights reserved.
//
import UIKit
// MARK: Enums and protocols
public extension PRSlideView {
enum ScrollDirection {
case horizontal
case vertical
}
}
public protocol PRSlideViewDataSource: class {
func numberOfPagesInSlideView(_ slideView: PRSlideView) -> Int
func slideView(_ slideView: PRSlideView, pageAt index: Int) -> PRSlideViewPage
}
public protocol PRSlideViewDelegate : UIScrollViewDelegate {
func slideView(_ slideView: PRSlideView, didScrollToPageAt index: Int)
func slideView(_ slideView: PRSlideView, didClickPageAt index: Int)
}
private extension PRSlideViewDelegate {
// Make these protocol functions optional
func slideView(_ slideView: PRSlideView, didScrollToPageAt index: Int) {}
func slideView(_ slideView: PRSlideView, didClickPageAt index: Int) {}
}
// MARK: - Main implementation
open class PRSlideView: UIView {
// MARK: Constants
private let bufferLength = 512
private let pageControlHeight: CGFloat = 17.0
// MARK: Protocols
weak open var dataSource: PRSlideViewDataSource?
weak open var delegate: PRSlideViewDelegate?
// MARK: Configs
open private(set) var scrollDirection: PRSlideView.ScrollDirection = .horizontal
open private(set) var infiniteScrollingEnabled: Bool = false
open var showsPageControl: Bool = true {
didSet {
updatePageControlHiddenStatus()
}
}
// MARK: Private properties
private var currentPagePhysicalIndex: Int = 0 {
didSet {
if oldValue != currentPagePhysicalIndex {
didScrollToPage(physicallyAt: currentPagePhysicalIndex)
}
}
}
private var baseIndexOffset: Int = 0
private var classForIdentifiers: [String: PRSlideViewPage.Type] = [:]
private var reusablePages: [String: Set<PRSlideViewPage>] = [:]
private var loadedPages: Set<PRSlideViewPage> = []
// MARK: UI elements and layouts
public let scrollView: UIScrollView = {
let view = UIScrollView()
view.clipsToBounds = false
view.isPagingEnabled = true
view.showsHorizontalScrollIndicator = false
view.showsVerticalScrollIndicator = false
view.scrollsToTop = false
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
open var pageControl: UIPageControl = {
let control = UIPageControl()
control.hidesForSinglePage = true
control.addTarget(self,
action: #selector(pageControlValueChanged(_:)),
for: .valueChanged)
control.translatesAutoresizingMaskIntoConstraints = false
return control
}()
private var horizontalLayout: [NSLayoutConstraint] {
return [
NSLayoutConstraint(item: containerView,
attribute: .width,
relatedBy: .equal,
toItem: scrollView,
attribute: .width,
multiplier: CGFloat(numberOfPages * (infiniteScrollingEnabled ? bufferLength : 1)),
constant: 0),
NSLayoutConstraint(item: containerView,
attribute: .height,
relatedBy: .equal,
toItem: scrollView,
attribute: .height,
multiplier: 1,
constant: 0)
]
}
private var verticalLayout: [NSLayoutConstraint] {
return [
NSLayoutConstraint(item: containerView,
attribute: .width,
relatedBy: .equal,
toItem: scrollView,
attribute: .width,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: containerView,
attribute: .height,
relatedBy: .equal,
toItem: scrollView,
attribute: .height,
multiplier: CGFloat(numberOfPages * (infiniteScrollingEnabled ? bufferLength : 1)),
constant: 0)
]
}
private var cachedLayout: [NSLayoutConstraint]?
private func layoutContainerView() {
let index = currentPagePhysicalIndex
if let layout = cachedLayout {
NSLayoutConstraint.deactivate(layout)
}
switch scrollDirection {
case .horizontal:
let layout = horizontalLayout
cachedLayout = layout
NSLayoutConstraint.activate(layout)
case .vertical:
let layout = verticalLayout
cachedLayout = layout
NSLayoutConstraint.activate(layout)
}
scrollToPage(physicallyAt: index, animated: false)
}
private var containerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: Access status
open var currentPageIndex: Int {
return index(forPhysical: currentPagePhysicalIndex)
}
open private(set) var numberOfPages: Int = 0 {
didSet {
layoutContainerView()
updatePageControlHiddenStatus()
pageControl.numberOfPages = numberOfPages
baseIndexOffset = infiniteScrollingEnabled ? numberOfPages * bufferLength / 2 : 0
}
}
// MARK: Access contents
open func page(at index: Int) -> PRSlideViewPage? {
return loadedPages.filter { $0.pageIndex == index }.first ?? nil
}
open func index(for page: PRSlideViewPage) -> Int {
return page.pageIndex
}
open var visiblePages: [PRSlideViewPage] {
return loadedPages.sorted { $0.pageIndex < $1.pageIndex }
}
// MARK: UI Control
open func scrollToPage(at index: Int) {
// Enable animation by default
scrollToPage(at: index, animated: true)
}
open func scrollToPage(at index: Int, animated: Bool) {
// Scroll to page in current loop by default
scrollToPage(physicallyAt: physicalIndexInCurrentLoop(for: index),
animated: animated)
}
open func scrollToPage(at index: Int, forward: Bool, animated: Bool) {
scrollToPage(physicallyAt: physicalIndex(for: index, forward: forward),
animated: animated)
}
open func scrollToPreviousPage() {
// Enable animation by default
scrollToPreviousPage(animated: true)
}
open func scrollToNextPage() {
// Enable animation by default
scrollToNextPage(animated: true)
}
open func scrollToPreviousPage(animated: Bool) {
scrollToPage(at: currentPageIndex - 1, forward: false, animated: animated)
}
open func scrollToNextPage(animated: Bool) {
scrollToPage(at: currentPageIndex + 1, forward: true, animated: animated)
}
open private(set) var isAutoScrollingEnabled: Bool = false
open var autoScrollingTimeInterval: TimeInterval = 5.0
open var autoScrollingRunLoopMode: RunLoop.Mode = .default
private var autoScrollingTimer: Timer?
open func startAutoScrolling() {
startAutoScrolling(withTimeInterval: autoScrollingTimeInterval,
withRunLoopMode: autoScrollingRunLoopMode)
}
open func startAutoScrolling(withTimeInterval interval: TimeInterval) {
startAutoScrolling(withTimeInterval: interval,
withRunLoopMode: autoScrollingRunLoopMode)
}
open func startAutoScrolling(withRunLoopMode mode: RunLoop.Mode) {
startAutoScrolling(withTimeInterval: autoScrollingTimeInterval,
withRunLoopMode: mode)
}
open func startAutoScrolling(withTimeInterval interval: TimeInterval, withRunLoopMode mode: RunLoop.Mode) {
autoScrollingTimer?.invalidate()
isAutoScrollingEnabled = true
autoScrollingTimeInterval = interval
autoScrollingRunLoopMode = mode
autoScrollingTimer = {
let timer = Timer(timeInterval: interval,
repeats: true,
block: { [weak self] timer in
guard let `self` = self else {
timer.invalidate()
return
}
self.scrollToNextPage()
})
RunLoop.main.add(timer,
forMode: mode)
return timer
}()
}
open func stopAutoScrolling() {
autoScrollingTimer?.invalidate()
isAutoScrollingEnabled = false
}
// MARK: Data control
open func reloadData() {
// Check data source
guard let dataSource = dataSource else {
fatalError("Slide view must have a data source")
}
// Load number of pages
numberOfPages = dataSource.numberOfPagesInSlideView(self)
guard numberOfPages != 0 else { return }
// Load pages by triggering didScrollToPage(physicallyAt:)
if infiniteScrollingEnabled && currentPageIndex == 0 {
// Reset position to middle if infinite scrolling is enabled and current page is the first one
scrollToPage(physicallyAt: baseIndexOffset, animated: false) // will trigger didScrollToPage(physicallyAt:)
} else {
didScrollToPage(physicallyAt: currentPagePhysicalIndex)
}
}
// MARK: Reuse
open func register(_ class: PRSlideViewPage.Type, forPageReuseIdentifier identifier: String) {
classForIdentifiers[identifier] = `class`
reusablePages[identifier] = []
}
open func dequeueReusablePage(withIdentifier identifier: String, for index: Int) -> PRSlideViewPage {
let page: PRSlideViewPage = {
if let page = reusablePages[identifier]?.popFirst() {
return page
} else if let page = classForIdentifiers[identifier]?.init(identifier: identifier) {
page.translatesAutoresizingMaskIntoConstraints = false
return page
}
fatalError("Unable to dequeue a page with identifier, must register a class for the identifier")
}()
page.pageIndex = index
loadedPages.insert(page)
return page
}
// MARK: Layout
private var firstLayout: Bool = true
private var isChangingLayout: Bool = false
open override func layoutSubviews() {
if firstLayout {
firstLayout = false
let index = currentPageIndex
super.layoutSubviews()
scrollToPage(physicallyAt: baseIndexOffset + index, animated: false)
} else {
isChangingLayout = true
let physicalIndex = currentPagePhysicalIndex
super.layoutSubviews()
scrollToPage(physicallyAt: physicalIndex, animated: false)
isChangingLayout = false
}
}
// MARK: Life cycle
private func configure() {
scrollView.delegate = self
addSubview(scrollView)
scrollView.insertSubview(containerView, at: 0)
addSubview(pageControl)
}
private func setupLayout() {
// Set up scroll view
do {
let attributes: [NSLayoutConstraint.Attribute] = [.top, .bottom, .leading, .trailing]
NSLayoutConstraint.activate(attributes.map {
return NSLayoutConstraint(item: scrollView,
attribute: $0,
relatedBy: .equal,
toItem: self,
attribute: $0,
multiplier: 1,
constant: 0)
})
}
// Set up container view
do {
let attributes: [NSLayoutConstraint.Attribute] = [.top, .bottom, .leading, .trailing]
NSLayoutConstraint.activate(attributes.map {
NSLayoutConstraint(item: containerView,
attribute: $0,
relatedBy: .equal,
toItem: scrollView,
attribute: $0,
multiplier: 1,
constant: 0)
})
}
// Set up page control
do {
let attributes: [NSLayoutConstraint.Attribute] = [.bottom, .leading, .trailing]
NSLayoutConstraint.activate(attributes.map {
return NSLayoutConstraint(item: pageControl,
attribute: $0,
relatedBy: .equal,
toItem: self,
attribute: $0,
multiplier: 1,
constant: 0)
} + [
NSLayoutConstraint(item: pageControl,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: pageControlHeight)
])
}
}
required public init(direction: ScrollDirection, infiniteScrolling enabled: Bool) {
self.scrollDirection = direction
self.infiniteScrollingEnabled = enabled
super.init(frame: .zero)
self.configure()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func willMove(toSuperview newSuperview: UIView?) {
// Reset first layout to true in case the new superview has not been layouted
firstLayout = true
}
open override func didMoveToSuperview() {
// Add constraints again when added to a superview
// Reference: func removeFromSuperview()
// > Calling this method removes any constraints that refer to the view you are removing,
// > or that refer to any view in the subtree of the view you are removing.
setupLayout()
}
}
// MARK: - Internal control
private extension PRSlideView {
// MARK: Control pages
func addPages(physicallyAt indexRange: Range<Int>) {
// If infinite scrolling is disabled, do not add pages off the limit
let physicalIndexRange = infiniteScrollingEnabled ? indexRange : indexRange.clamped(to: 0 ..< numberOfPages)
// Add pages
for physicalIndex in physicalIndexRange {
let index = self.index(forPhysical: physicalIndex)
// Continue if the page already exists
guard page(at: index) == nil else { continue }
// Check data source
guard let dataSource = dataSource else {
fatalError("Slide view must have a data source")
}
// Create page
let page = dataSource.slideView(self, pageAt: index)
page.pageIndex = index
page.addTarget(self,
action: #selector(pageClicked(_:)),
for: .touchUpInside)
// Add page
loadedPages.insert(page)
// Just in case someone inexperienced doesn't call reloadData() from main thread
DispatchQueue.main.async { [weak self] in
guard let `self` = self else { return }
self.containerView.addSubview(page)
NSLayoutConstraint.activate([
NSLayoutConstraint(item: page,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: page,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .height,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: page,
attribute: self.scrollDirection == .horizontal ? .centerY : .centerX,
relatedBy: .equal,
toItem: self.containerView,
attribute: self.scrollDirection == .horizontal ? .centerY : .centerX,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: page,
attribute: self.scrollDirection == .horizontal ? .centerX : .centerY,
relatedBy: .equal,
toItem: self.containerView,
attribute: self.scrollDirection == .horizontal ? .centerX : .centerY,
multiplier: self.numberOfPages == 0 ? 1 : CGFloat(physicalIndex * 2 + 1) / CGFloat(self.numberOfPages * (self.infiniteScrollingEnabled ? self.bufferLength : 1)),
constant: 0)
])
}
}
}
func removePages(physicallyOutOf indexRange: Range<Int>) {
for page in loadedPages.filter({ !(indexRange ~= $0.pageIndex) }) {
// Move page to reuse pool
guard var pages = reusablePages[page.pageIdentifier] else {
fatalError("Unable to reuse a page with identifier, must register a class for the identifier")
}
pages.insert(page)
// Just in case someone inexperienced doesn't call reloadData() from main thread
DispatchQueue.main.async {
page.removeFromSuperview()
}
loadedPages.remove(page)
}
}
func didScrollToPage(physicallyAt index: Int) {
// Call delegate
delegate?.slideView(self, didScrollToPageAt: self.index(forPhysical: index))
// Load 3 pages: previous + current + next
let range = index - 1 ..< index + 1 + 1
removePages(physicallyOutOf: range)
addPages(physicallyAt: range)
}
// MARK: Scroll
func scrollToPage(physicallyAt index: Int) {
// Enable animation by default
scrollToPage(physicallyAt: index, animated: true)
}
func scrollToPage(physicallyAt index: Int, animated: Bool) {
scrollView.setContentOffset(rectForPage(physicallyAt: index).origin,
animated: animated)
}
// MARK: Index and frame handling
func physicalIndexInCurrentLoop(for index: Int) -> Int {
guard infiniteScrollingEnabled else {
return index
}
return currentPagePhysicalIndex - currentPageIndex + index
}
func physicalIndex(for index: Int, forward: Bool) -> Int {
guard infiniteScrollingEnabled else {
return index
}
let offset = index - currentPageIndex
let physicalIndexInLoop = currentPagePhysicalIndex + offset
if forward && offset < 0 {
return physicalIndexInLoop + numberOfPages
} else if !forward && offset > 0 {
return physicalIndexInLoop - numberOfPages
}
return physicalIndexInLoop
}
func index(forPhysical index: Int) -> Int {
guard numberOfPages != 0 else {
return 0
}
var index = index
if infiniteScrollingEnabled {
index = index % numberOfPages
if index < 0 {
index += numberOfPages
}
}
return index
}
func rectForPage(physicallyAt index: Int) -> CGRect {
return CGRect(origin: CGPoint(x: scrollDirection == .horizontal ? bounds.width * CGFloat(index) : 0,
y: scrollDirection == .vertical ? bounds.height * CGFloat(index) : 0),
size: bounds.size)
}
// MARK: UI Control
func updatePageControlHiddenStatus() {
if (showsPageControl
&& scrollDirection == .horizontal
&& bounds.width <= pageControl.size(forNumberOfPages: numberOfPages).width) {
// TODO: Shows page number instead when there are too many pages
pageControl.isHidden = false
} else {
pageControl.isHidden = true
}
}
}
// MARK: - Actions
private extension PRSlideView {
@objc func pageClicked(_ page: PRSlideViewPage) {
delegate?.slideView(self, didClickPageAt: index(forPhysical: page.pageIndex))
}
@objc func pageControlValueChanged(_ pageControl: UIPageControl) {
scrollToPage(at: pageControl.currentPage)
}
}
// MARK: - Scroll view delegate
extension PRSlideView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
guard firstLayout == false else { return }
guard isChangingLayout == false else { return }
let offset = scrollView.contentOffset
currentPagePhysicalIndex = {
switch scrollDirection {
case .horizontal:
let width = bounds.width
return Int((offset.x + width * 0.5) / width)
case .vertical:
let height = bounds.height
return Int((offset.y + height * 0.5) / height)
}
}()
}
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
if isAutoScrollingEnabled {
autoScrollingTimer?.invalidate()
}
}
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == self.scrollView {
if isAutoScrollingEnabled {
startAutoScrolling(withTimeInterval: autoScrollingTimeInterval,
withRunLoopMode: autoScrollingRunLoopMode)
}
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
pageControl.currentPage = currentPageIndex
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == self.scrollView {
pageControl.currentPage = currentPageIndex
}
}
}
| mit | 1d6ed22b2811e31a9dc7bcd5d487d84a | 36.275272 | 200 | 0.545144 | 5.852991 | false | false | false | false |
wiltonlazary/kotlin-native | performance/KotlinVsSwift/ring/src/WithIndiciesBenchmark.swift | 4 | 973 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import Foundation
class WithIndiciesBenchmark {
private var _data: [Value]? = nil
var data: [Value] {
get {
return _data!
}
}
init() {
var list: [Value] = []
for n in classValues(Constants.BENCHMARK_SIZE) {
list.append(n)
}
_data = list
}
func withIndicies() {
for (index, value) in data.lazy.enumerated() {
if (filterLoad(value)) {
Blackhole.consume(index)
Blackhole.consume(value)
}
}
}
func withIndiciesManual() {
var index = 0
for value in data {
if (filterLoad(value)) {
Blackhole.consume(index)
Blackhole.consume(value)
}
index += 1
}
}
}
| apache-2.0 | ccccc2e8773e2dcffa8971122705d2ba | 21.627907 | 101 | 0.502569 | 4.140426 | false | false | false | false |
loudnate/xDripG5 | ResetTransmitter/Views/Button.swift | 1 | 1084 | //
// Button.swift
// ResetTransmitter
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import UIKit
class Button: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = tintColor
layer.cornerRadius = 6
titleLabel?.adjustsFontForContentSizeCategory = true
contentEdgeInsets.top = 14
contentEdgeInsets.bottom = 14
setTitleColor(.white, for: .normal)
}
override func tintColorDidChange() {
super.tintColorDidChange()
backgroundColor = tintColor
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
tintColor = .blue
tintColorDidChange()
}
override var isHighlighted: Bool {
didSet {
alpha = isHighlighted ? 0.5 : 1
}
}
override var isEnabled: Bool {
didSet {
tintAdjustmentMode = isEnabled ? .automatic : .dimmed
}
}
}
| mit | 08b287ac19c54a362f7b49dab9ba65cd | 19.433962 | 65 | 0.612188 | 5.308824 | false | false | false | false |
usbong/UsbongKit | UsbongKit/Views/Modules/RadioTableViewCell.swift | 2 | 1168 | //
// RadioTableViewCell.swift
// UsbongKit
//
// Created by Joe Amanse on 27/11/2015.
// Copyright © 2015 Usbong Social Systems, Inc. All rights reserved.
//
import UIKit
open class RadioTableViewCell: UITableViewCell, NibReusable {
@IBOutlet open weak var radioButton: RadioButton!
@IBOutlet open weak var titleLabel: UILabel!
open var radioButtonSelected: Bool {
get {
return radioButton.isSelected
}
set {
radioButton.isSelected = newValue
}
}
override open func awakeFromNib() {
super.awakeFromNib()
// Initialization code
radioButton.fillCircleColor = UIColor.darkGray
radioButton.circleColor = UIColor.black
radioButton.circleLineWidth = 1.0
}
override open func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
open override func prepareForReuse() {
// let oldValue = radioButton.selected
radioButton.isSelected = false
super.prepareForReuse()
}
}
| apache-2.0 | 334ff9e96a06acbb877c416c7b7c6787 | 24.369565 | 70 | 0.637532 | 5.140969 | false | false | false | false |
huahuasj/ios-charts | Charts/Classes/Data/CombinedChartData.swift | 6 | 4199 | //
// CombinedChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/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
public class CombinedChartData: BarLineScatterCandleChartData
{
private var _lineData: LineChartData!
private var _barData: BarChartData!
private var _scatterData: ScatterChartData!
private var _candleData: CandleChartData!
private var _bubbleData: BubbleChartData!
public override init()
{
super.init();
}
public override init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets);
}
public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets);
}
public var lineData: LineChartData!
{
get
{
return _lineData;
}
set
{
_lineData = newValue;
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet);
}
checkIsLegal(newValue.dataSets);
calcMinMax(start: _lastStart, end: _lastEnd);
calcYValueSum();
calcYValueCount();
calcXValAverageLength();
}
}
public var barData: BarChartData!
{
get
{
return _barData;
}
set
{
_barData = newValue;
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet);
}
checkIsLegal(newValue.dataSets);
calcMinMax(start: _lastStart, end: _lastEnd);
calcYValueSum();
calcYValueCount();
calcXValAverageLength();
}
}
public var scatterData: ScatterChartData!
{
get
{
return _scatterData;
}
set
{
_scatterData = newValue;
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet);
}
checkIsLegal(newValue.dataSets);
calcMinMax(start: _lastStart, end: _lastEnd);
calcYValueSum();
calcYValueCount();
calcXValAverageLength();
}
}
public var candleData: CandleChartData!
{
get
{
return _candleData;
}
set
{
_candleData = newValue;
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet);
}
checkIsLegal(newValue.dataSets);
calcMinMax(start: _lastStart, end: _lastEnd);
calcYValueSum();
calcYValueCount();
calcXValAverageLength();
}
}
public var bubbleData: BubbleChartData!
{
get
{
return _bubbleData;
}
set
{
_bubbleData = newValue;
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet);
}
checkIsLegal(newValue.dataSets);
calcMinMax(start: _lastStart, end: _lastEnd);
calcYValueSum();
calcYValueCount();
calcXValAverageLength();
}
}
public override func notifyDataChanged()
{
if (_lineData !== nil)
{
_lineData.notifyDataChanged();
}
if (_barData !== nil)
{
_barData.notifyDataChanged();
}
if (_scatterData !== nil)
{
_scatterData.notifyDataChanged();
}
if (_candleData !== nil)
{
_candleData.notifyDataChanged();
}
if (_bubbleData !== nil)
{
_bubbleData.notifyDataChanged();
}
}
}
| apache-2.0 | e85ecf51cfc86e0bc7fc7e7c2863243e | 22.071429 | 71 | 0.480829 | 5.736339 | false | false | false | false |
lilongcnc/Swift-weibo2015 | ILWEIBO04/ILWEIBO04/Classes/UI/OAuth/OAuthViewController.swift | 1 | 5067 | //
// OAuthViewController.swift
// 02-TDD
//
// Created by apple on 15/2/28.
// Copyright (c) 2015年 heima. All rights reserved.
//
import UIKit
// 发送通知的请求
let WB_Login_Successed_Notification = "WB_Login_Successed_Notification"
class OAuthViewController: UIViewController {
let WB_API_URL_String = "https://api.weibo.com"
let WB_Redirect_URL_String = "http://www.baidu.com"
let WB_Client_ID = "2105659899"
let WB_Client_Secret = "8207985f2251507de62c0e3374d1e6d1"
let WB_Grant_Type = "authorization_code"
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
loadAuthPage()
}
/// 加载授权页面
func loadAuthPage() {
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL_String)"
let url = NSURL(string: urlString)
webView.loadRequest(NSURLRequest(URL: url!))
}
}
extension OAuthViewController: UIWebViewDelegate {
//MARK:用不到的方法
func webViewDidStartLoad(webView: UIWebView) {
// println(__FUNCTION__)
}
func webViewDidFinishLoad(webView: UIWebView) {
// println(__FUNCTION__)
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
// println(__FUNCTION__)
}
/// 页面重定向
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
println(request.URL)
//获取accesstoken
let result = continueWithCode(request.URL!)
if let code = result.code {
println("可以换 accesstoken \(code)")
let params = ["client_id": WB_Client_ID,
"client_secret": WB_Client_Secret,
"grant_type": WB_Grant_Type,
"redirect_uri": WB_Redirect_URL_String,
"code": code]
//发送网络请求
let net = NetWorkManager.instance
net.requestJSON(HTTPMethod.POST, "https://api.weibo.com/oauth2/access_token", params ) { (result, error) -> () in
let token = AccessTokenModel(dict: result as! NSDictionary)
token.saveAccessToken()
//MARK: 获取并保存用户token.access_token之后,我们从登陆界面跳转到主界面
// 用来通知 告诉 AppDeleagte 进行切换 视图界面
NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Successed_Notification, object: nil)
// println(token.access_token)
// println(result)
}
}
if !result.load {
/**
如果不加载页面,需要重新刷新授权页面
直接只写loadAuthPage(),有可能出县多次加载页面
当我们先点击取消之后,就不能点击授权按钮了,所以我们需要在点击刷新之后,对页面进行刷新
*/
//只有点击授权页面的取消按钮才重新刷新当前页面
if result.reloadPage {
SVProgressHUD.showErrorWithStatus("你真的要拒绝吗?点击授权有更多惊喜哦~~~你懂的", maskType: SVProgressHUDMaskType.Gradient)
loadAuthPage()
}
}
return result.load
}
//// 根据URL判断是否继续
///
/// :param: url URL
///
/// :returns: 1. 是否加载当前页面 2. code(如果有) 3. 是否刷新授权页面
/// 返回:是否加载,如果有 code,同时返回 code,否则返回 nil
func continueWithCode(url: NSURL) -> (load: Bool, code: String?,reloadPage : Bool) {
// 1. 将url转换成字符串
let urlString = url.absoluteString!
// 2. 如果不是微博的 api 地址,都不加载
if !urlString.hasPrefix(WB_API_URL_String) {
// 3. 如果是回调地址,需要判断 code
if urlString.hasPrefix(WB_Redirect_URL_String) {
if let query = url.query {
let codestr: NSString = "code="
// 访问新浪微博授权的时候,带有回调地址的url只有两个,一个是正确的,一个是错误的!
if query.hasPrefix(codestr as String) {
var q = query as NSString!
return (false, q.substringFromIndex(codestr.length),false)
}else{
//说明点击取消,发送的错误的链接,没有code=
return (false, nil, true)
}
}
}
return (false, nil,false)
}
return (true, nil,false)
}
}
| mit | 25df02fb367ddd6e7a315bcaa08469ed | 30.705036 | 137 | 0.540277 | 4.130272 | false | false | false | false |
solinor/paymenthighway-ios-framework | PaymentHighway/UI/ExpirationDateTextField.swift | 1 | 1829 | //
// ExpiryDateTextField.swift
// PaymentHighway
//
// Copyright © 2018 Payment Highway Oy. All rights reserved.
//
/// Specialized text field for collecting expiration date.
///
open class ExpiryDateTextField: TextField {
private var cardExpiryDateDeleting = false
private lazy var expiryDatePicker: ExpiryDatePickerView = {
let picker = ExpiryDatePickerView()
return picker
}()
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
textFieldType = TextFieldType.expiryDate
delegate = self
placeholder = NSLocalizedString("MM/YY", bundle: Bundle(for: type(of: self)), comment: "Expiration date placeholder.")
format = { [weak self] (text) in
return ExpiryDate.format(expiryDate: text, deleting: self?.cardExpiryDateDeleting ?? false)
}
validate = ExpiryDate.isValid
if theme.expiryDatePicker {
inputView = expiryDatePicker
expiryDatePicker.onDateSelected = { (month, year) in
let newText = String(format: "%02d/%02d", month, year - 2000)
self.isValid = self.validate(newText)
self.text = newText
}
}
}
open override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let char = string.cString(using: .utf8) {
let isBackSpace = strcmp(char, "\\b")
cardExpiryDateDeleting = (isBackSpace == -92) ? true : false
}
return super.textField(textField, shouldChangeCharactersIn: range, replacementString: string)
}
open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return !theme.expiryDatePicker
}
}
| mit | 9fc1dab6f01cc3050b4fffac637519a9 | 36.306122 | 143 | 0.644967 | 4.874667 | false | false | false | false |
firebase/quickstart-ios | messaging/MessagingExampleSwift/ViewController.swift | 1 | 2188 | //
// Copyright (c) 2016 Google 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 UIKit
import FirebaseMessaging
@objc(ViewController)
class ViewController: UIViewController {
@IBOutlet var fcmTokenMessage: UILabel!
@IBOutlet var remoteFCMTokenMessage: UILabel!
override func viewDidLoad() {
NotificationCenter.default.addObserver(
self,
selector: #selector(displayFCMToken(notification:)),
name: Notification.Name("FCMToken"),
object: nil
)
}
@IBAction func handleLogTokenTouch(_ sender: UIButton) {
// [START log_fcm_reg_token]
let token = Messaging.messaging().fcmToken
print("FCM token: \(token ?? "")")
// [END log_fcm_reg_token]
fcmTokenMessage.text = "Logged FCM token: \(token ?? "")"
// [START log_iid_reg_token]
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching remote FCM registration token: \(error)")
} else if let token = token {
print("Remote instance ID token: \(token)")
self.remoteFCMTokenMessage.text = "Remote FCM registration token: \(token)"
}
}
// [END log_iid_reg_token]
}
@IBAction func handleSubscribeTouch(_ sender: UIButton) {
// [START subscribe_topic]
Messaging.messaging().subscribe(toTopic: "weather") { error in
print("Subscribed to weather topic")
}
// [END subscribe_topic]
}
@objc func displayFCMToken(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
if let fcmToken = userInfo["token"] as? String {
fcmTokenMessage.text = "Received FCM token: \(fcmToken)"
}
}
}
| apache-2.0 | e345043dfd4fdd76137305de97f932be | 31.656716 | 83 | 0.680073 | 4.029466 | false | false | false | false |
Liujlai/DouYuD | DYTV/DYTV/AnchorGroup.swift | 1 | 1033 | //
// AnchorGroup.swift
// DYTV
//
// Created by idea on 2017/8/9.
// Copyright © 2017年 idea. All rights reserved.
//
import UIKit
class AnchorGroup: BaseGameModel {
// 该组中对应的房间信息
var room_list : [[String:NSObject]]? {
didSet{
guard let room_list = room_list else { return }
for dict in room_list {
anchors.append(AnchorModel(dict:dict))
}
}
}
// 组显示的图标
var icon_name :String = "home_herder_normal"
// 游戏对应的图标
// var icon_url :String = ""
// 定义主播的模型对象数组
lazy var anchors: [AnchorModel] = [AnchorModel]()
/**
override func setValue(_ value: Any?, forKey key: String) {
if key == "room_list" {
if let dataArray = value as? [[String: NSObject]] {
for dict in dataArray {
anchors.append(AnchorModel(dict:dict))
}
}
}
}
*/
}
| mit | 2f8b4bffee59a50fa7900480d836c8ff | 20.863636 | 63 | 0.509356 | 3.910569 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | Sources/GraphAPI/GraphRequestResponse.swift | 1 | 1185 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2017 ShopGun. All rights reserved.
import Foundation
public struct GraphResponse {
public var data: GraphDict?
public var errors: [GraphError]?
}
// MARK: - Request
public protocol GraphRequestProtocol {
var query: GraphQuery { get }
var timeoutInterval: TimeInterval { get }
var additionalHeaders: [String: String]? { get }
}
/// Generic, concrete request
public struct GraphRequest: GraphRequestProtocol {
public let query: GraphQuery
public let timeoutInterval: TimeInterval
public let additionalHeaders: [String: String]?
public init(query: GraphQuery, timeoutInterval: TimeInterval = 30, additionalHeaders: [String: String]? = nil) {
self.query = query
self.timeoutInterval = timeoutInterval
self.additionalHeaders = additionalHeaders
}
}
| mit | 1c46f976f1e01d3490741d86ef756ccd | 26.861111 | 116 | 0.594217 | 4.110656 | false | false | false | false |
snoms/FinalProject | Trip/Trip/RouteManager.swift | 1 | 5652 | //
// RouteManager.swift
// Trip
//
// Created by bob on 09/06/16.
// Copyright © 2016 bob. All rights reserved.
//
// Singleton class serving as route manager. A route is loaded in
// and subsequently available throughout the application. Provides
// several methods which implement region monitoring functionality
// for journey points of interest.
//
import Foundation
import PXGoogleDirections
import CoreLocation
import SwiftLocation
class RouteManager {
// initiate singleton as sharedInstance
static let sharedInstance = RouteManager()
private init() { }
// declare private variables for the route, its fences and the relevant regions
private var plannedRoute: [PXGoogleDirectionsRoute]?
private var transitFences: [TransitFence]? = []
private var fenceRegions: [RegionRequest]? = []
// function to expose route
func getRoute() -> [PXGoogleDirectionsRoute]? {
if plannedRoute != nil {
return plannedRoute
}
else {
return nil
}
}
func clearRoute() {
stopMonitoring()
plannedRoute = []
transitFences = []
fenceRegions = []
}
func stopMonitoring() {
if fenceRegions != nil {
for fence in fenceRegions! {
BeaconManager.shared.stopMonitorGeographicRegion(request: fence)
}
}
}
// function to load route and execute fence extraction sequence, and start monitoring
func setRoute(newRoute: [PXGoogleDirectionsRoute]) {
clearRoute()
plannedRoute = newRoute
detectTransitStops()
startMonitoring()
}
// appending the fences of the route to our array of fences
func appendFence(transitFence: TransitFence) {
if plannedRoute != nil {
RouteManager.sharedInstance.transitFences?.append(transitFence)
}
else {
print("no route to append fence")
}
}
// function to extract the pertinent transit stops and create fences
func detectTransitStops() {
if getRoute() != nil {
for (index, step) in ((getRoute()?.first!.legs.first!.steps)?.enumerate())! {
if step.transitDetails != nil {
if step.travelMode == PXGoogleDirectionsMode.Transit {
var newRadius: CLLocationDistance = 500.00
let vehicleType = step.transitDetails?.line?.vehicle?.type!
switch vehicleType! {
case PXGoogleDirectionsVehicleType.CommuterTrain, PXGoogleDirectionsVehicleType.HeavyRail, PXGoogleDirectionsVehicleType.HighSpeedTrain : newRadius = 3000.00
case PXGoogleDirectionsVehicleType.Subway : newRadius = 700.00
case PXGoogleDirectionsVehicleType.Tram : newRadius = 500.00
case PXGoogleDirectionsVehicleType.Bus : newRadius = 350.00
default : break
}
let newFence = TransitFence(coordinate: step.transitDetails!.arrivalStop!.location!, radius: newRadius, identifier: index, stop: (step.transitDetails!.arrivalStop?.description)!)
appendFence(newFence)
}
}
}
}
}
// initiate region monitoring for our fences
func startMonitoring() {
if transitFences != nil {
for (index, fence) in transitFences!.enumerate() {
do {
let newfence = try BeaconManager.shared.monitorGeographicRegion(fence.stop, centeredAt: fence.coordinate, radius: fence.radius, onEnter: { temp in
// post notification through notification center for when user is in app
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("fenceProx", object: nil, userInfo: ["message":fence.stop])
// create notification to be pushed locally when app is in background
if UIApplication.sharedApplication()
.applicationState != UIApplicationState.Active {
let notification = UILocalNotification()
notification.alertBody = "Wake up, you're approaching \(fence.stop). Get ready!"
notification.alertAction = "Open Trip"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["message":fence.stop]
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
}, onExit: { temp2 in
if index == self.transitFences!.count {
self.stopMonitoring()
}
})
fenceRegions!.append(newfence)
try self.fenceRegions!.first?.start()
} catch {
print(error)
}
}
}
}
func methodOfReceivedNotification(notification: NSNotification){
//Take Action on Notification
print("notification received!")
}
func getTransitFences() -> [TransitFence]? {
if transitFences != nil {
return transitFences
}
else {
return nil
}
}
} | mit | b36f172aade680c81ad405e1658181b3 | 37.189189 | 202 | 0.560786 | 5.611718 | false | false | false | false |
ByteriX/BxInputController | BxInputController/Sources/Rows/Variants/View/BxInputSearchVariantRowBinder.swift | 1 | 2617 | //
// BxInputSearchVariantRowBinder.swift
// BxInputController
//
// Created by Sergey Balalaev on 10/01/2019.
// Copyright © 2019 Byterix. All rights reserved.
//
import UIKit
open class BxInputSearchVariantRowBinder<T: BxInputStringObject, Row: BxInputSearchVariantRow<T>, Cell: BxInputSelectorCell>: BxInputSelectorVariantRowBinder<T, Row, Cell>, UITextFieldDelegate
{
override open func update() {
super.update()
//
cell?.valueTextField.changeTarget(self, action: #selector(valueChanged(valueTextField:)), for: .editingChanged)
cell?.valueTextField.delegate = self
cell?.valueTextField.update(from: BxInputTextSettings.standart)
}
override open func didSelected()
{
super.didSelected()
if row.isEnabled {
if row.isOpened {
cell?.valueTextField.isUserInteractionEnabled = true
cell?.valueTextField.becomeFirstResponder()
} else {
cell?.valueTextField.resignFirstResponder()
cell?.valueTextField.isUserInteractionEnabled = false
}
}
}
/// event when value is changed. Need reload this in inherited classes
@objc open func valueChanged(valueTextField: UITextField) {
if let searchHandler = row.searchHandler {
if let text = valueTextField.text {
row.items = searchHandler(row, text)
} else {
row.items = []
}
if let parentRowBinder = owner?.getRowBinder(for: row.child) as? BxInputChildSelectorVariantRowBinder<T> {
parentRowBinder.updateItems()
if row.items.count == 1 && row.value !== row.items.first {
parentRowBinder.selectValue(from: 0)
}
}
}
}
/// changing value event for correct showing
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if let text = textField.text,
range.location == text.chars.count && string == " "
{
textField.text = text + "\u{00a0}"
return false
}
return true
}
/// clear event, when user click clear button
open func textFieldShouldClear(_ textField: UITextField) -> Bool
{
textField.text = ""
return true
}
/// user click Done
open func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
}
| mit | 08968277684727538e447a9c50d4a87d | 32.113924 | 192 | 0.607416 | 4.935849 | false | false | false | false |
natestedman/PropertyComposition | PropertyCompositionTests/PropertyCompositionTests.swift | 1 | 1320 | // PropertyComposition
// Written in 2016 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import PropertyComposition
import ReactiveCocoa
import XCTest
class PropertyCompositionTests: XCTestCase
{
func testMap()
{
let property = MutableProperty(0)
let mapped = property.map({ $0 + 1 })
XCTAssertEqual(mapped.value, 1)
property.value = 1
XCTAssertEqual(mapped.value, 2)
}
func testCombineLatestWith()
{
let properties = (MutableProperty(0), MutableProperty(0))
let combined = properties.0.combineLatestWith(properties.1)
XCTAssertEqual(combined.value.0, 0)
XCTAssertEqual(combined.value.1, 0)
properties.0.value = 1
XCTAssertEqual(combined.value.0, 1)
XCTAssertEqual(combined.value.1, 0)
properties.1.value = 1
XCTAssertEqual(combined.value.0, 1)
XCTAssertEqual(combined.value.1, 1)
}
}
| cc0-1.0 | 94c1ec84542b73df73c9ccc683ebf902 | 29.697674 | 83 | 0.690909 | 4.370861 | false | true | false | false |
ateliercw/AnglePanGestureRecognizer | AnglePanGestureRecognizer Example/TileView.swift | 1 | 1390 | //
// TileView.swift
// AnglePanGestureRecognizer
//
// Created by Matthew Buckley on 4/30/17.
// Copyright © 2017 Atelier Clockwork. All rights reserved.
//
import Foundation
import UIKit
class TileView: UIView {
let circleView: UIView = {
let view = UIView(frame: CGRect.zero)
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.borderColor = UIColor.black.cgColor
view.layer.borderWidth = .circleViewBorderWidth
view.layer.masksToBounds = true
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(circleView)
NSLayoutConstraint.activate([
circleView.topAnchor.constraint(equalTo: topAnchor, constant: 2.5),
circleView.leftAnchor.constraint(equalTo: leftAnchor, constant: 2.5),
bottomAnchor.constraint(equalTo: circleView.bottomAnchor, constant: 2.5),
rightAnchor.constraint(equalTo: circleView.rightAnchor, constant: 2.5)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
circleView.layer.cornerRadius = (frame.height / 2.0) - .circleViewBorderWidth
}
}
private extension CGFloat {
static let circleViewBorderWidth: CGFloat = 2.0
}
| mit | ecef0916cd1ffec3f7701c06d8496ad1 | 26.78 | 85 | 0.671706 | 4.599338 | false | false | false | false |
vimeo/VimeoUpload | VimeoUpload/Upload/Networking/Shared/VimeoRequestSerializer+SharedUpload.swift | 1 | 8955 | //
// VimeoRequestSerializer+SharedUpload.swift
// VimeoUpload
//
// Created by Alfred Hanssen on 10/21/15.
// Copyright © 2015 Vimeo. 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
import AVFoundation
import VimeoNetworking
extension VimeoRequestSerializer
{
private struct Constants
{
static let CreateVideoURI = "/me/videos"
static let TypeKey = "type"
static let SizeKey = "size"
static let MIMETypeKey = "mime_type"
}
func myVideosRequest() throws -> NSMutableURLRequest
{
let url = URL(string: "/me/videos", relativeTo: VimeoBaseURL)!
var error: NSError?
let request = self.request(withMethod: .get, urlString: url.absoluteString, parameters: nil, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.MyVideos.rawValue)
}
return request
}
func createVideoRequest(with url: URL, uploadType: VIMUpload.UploadApproach = VIMUpload.UploadApproach.Streaming) throws -> NSMutableURLRequest
{
var parameters = try self.createFileSizeParameters(url: url)
parameters[Constants.TypeKey] = uploadType.rawValue
let url = URL(string: Constants.CreateVideoURI, relativeTo: VimeoBaseURL)!
return try self.createVideoRequest(with: url, parameters: parameters)
}
func createVideoRequest(with url: URL, parameters: [String: Any]) throws -> NSMutableURLRequest
{
var error: NSError?
let request = self.request(withMethod: .post, urlString: url.absoluteString, parameters: parameters, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.Create.rawValue)
}
return request
}
func createFileSizeParameters(url: URL) throws -> [String: Any]
{
let asset = AVURLAsset(url: url)
let fileSize: Double
do
{
fileSize = try asset.fileSize()
}
catch let error as NSError
{
throw error.error(byAddingDomain: UploadErrorDomain.Create.rawValue)
}
let fileSizeString = fileSize
return [Constants.SizeKey: fileSizeString]
}
private func createMIMETypeParameters(url: URL) throws -> [String: Any]
{
let type: String
do
{
type = try url.mimeType()
}
catch let error as NSError
{
throw error.error(byAddingDomain: UploadErrorDomain.Create.rawValue)
}
return [Constants.MIMETypeKey: type]
}
func createFileParameters(url: URL) throws -> [String: Any]
{
let fileSizeParameters: [String: Any]
do
{
fileSizeParameters = try self.createFileSizeParameters(url: url)
}
catch let error as NSError
{
throw error.error(byAddingDomain: UploadErrorDomain.Create.rawValue)
}
let fileMIMETypeParameters: [String: Any]
do
{
fileMIMETypeParameters = try self.createMIMETypeParameters(url: url)
}
catch let error as NSError
{
throw error.error(byAddingDomain: UploadErrorDomain.Create.rawValue)
}
// Merge in the new key-value pairs passed in, favoring new values for any duplicate keys
return fileSizeParameters.merging(fileMIMETypeParameters) { (current, new) in new }
}
func uploadVideoRequest(with source: URL, destination: String) throws -> NSMutableURLRequest
{
guard FileManager.default.fileExists(atPath: source.path) else
{
throw NSError(domain: UploadErrorDomain.Upload.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "Attempt to construct upload request but the source file does not exist."])
}
var error: NSError?
let request = self.request(withMethod: .put, urlString: destination, parameters: nil, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.Upload.rawValue)
}
let asset = AVURLAsset(url: source)
let fileSize: Double
do
{
fileSize = try asset.fileSize()
}
catch let error as NSError
{
throw error.error(byAddingDomain: UploadErrorDomain.Upload.rawValue)
}
request.setValue("\(fileSize)", forHTTPHeaderField: "Content-Length")
request.setValue("video/mp4", forHTTPHeaderField: "Content-Type")
// For resumed uploads on a single upload ticket we must include this header per @naren (undocumented) [AH] 12/25/2015
request.setValue("bytes 0-\(fileSize)/\(fileSize)", forHTTPHeaderField: "Content-Range")
return request
}
func activateVideoRequest(withURI uri: String) throws -> NSMutableURLRequest
{
let url = URL(string: uri, relativeTo: VimeoBaseURL)!
var error: NSError?
let request = self.request(withMethod: .delete, urlString: url.absoluteString, parameters: nil, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.Activate.rawValue)
}
return request
}
func videoSettingsRequest(with videoUri: String, videoSettings: VideoSettings) throws -> NSMutableURLRequest
{
guard videoUri.isEmpty == false else
{
throw NSError(domain: UploadErrorDomain.VideoSettings.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "videoUri has length of 0."])
}
let url = URL(string: videoUri, relativeTo: VimeoBaseURL)!
var error: NSError?
let parameters = videoSettings.parameterDictionary()
if parameters.isEmpty
{
throw NSError(domain: UploadErrorDomain.VideoSettings.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "Parameters dictionary is empty."])
}
let request = self.request(withMethod: .patch, urlString: url.absoluteString, parameters: parameters, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.VideoSettings.rawValue)
}
return request
}
func deleteVideoRequest(with videoUri: String) throws -> NSMutableURLRequest
{
guard videoUri.isEmpty == false else
{
throw NSError(domain: UploadErrorDomain.Delete.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "videoUri has length of 0."])
}
let url = URL(string: videoUri, relativeTo: VimeoBaseURL)!
var error: NSError?
let request = self.request(withMethod: .delete, urlString: url.absoluteString, parameters: nil, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.Delete.rawValue)
}
return request
}
func videoRequest(with videoUri: String) throws -> NSMutableURLRequest
{
guard videoUri.isEmpty == false else
{
throw NSError(domain: UploadErrorDomain.Video.rawValue, code: 0, userInfo: [NSLocalizedDescriptionKey: "videoUri has length of 0."])
}
let url = URL(string: videoUri, relativeTo: VimeoBaseURL)!
var error: NSError?
let request = self.request(withMethod: .get, urlString: url.absoluteString, parameters: nil, error: &error)
if let error = error
{
throw error.error(byAddingDomain: UploadErrorDomain.Video.rawValue)
}
return request
}
}
| mit | d1b22aba006ce1ff95b8f60068567b7b | 34.816 | 191 | 0.638039 | 4.938776 | false | false | false | false |
vulgur/Sources | CodeReader/Model/Theme.swift | 1 | 368 | //
// Theme.swift
// CodeReader
//
// Created by vulgur on 16/6/11.
// Copyright © 2016年 MAD. All rights reserved.
//
import UIKit
class Theme {
var name: String!
var colors = [UIColor?]()
var isPurchased: Bool = true
required init(name: String, purchased: Bool = false) {
self.name = name
self.isPurchased = purchased
}
}
| mit | a3b0b5b1166e51d95e04310bd22d5e69 | 18.210526 | 58 | 0.613699 | 3.47619 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | WeCenterMobile/View/Sidebar/SidebarUserView.swift | 1 | 1135 | //
// SidebarUserView.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/5/29.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import GBDeviceInfo
import UIKit
class SidebarUserView: UIView {
@IBOutlet weak var userAvatarView: MSRRoundedImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userSignatureLabel: UILabel!
@IBOutlet weak var overlay: UIView!
func update(#user: User?) {
userAvatarView.wc_updateWithUser(user)
userNameLabel.text = user?.name ?? "加载中……"
userSignatureLabel.text = user?.signature ?? "说点什么吧……"
layoutIfNeeded()
}
lazy var minHeight: CGFloat = {
let display = GBDeviceInfo.deviceInfo().display
let heights: [GBDeviceDisplay: CGFloat] = [
.DisplayUnknown: 220,
.DisplayiPad: 220,
.DisplayiPhone35Inch: 170,
.DisplayiPhone4Inch: 170,
.DisplayiPhone47Inch: 200,
.DisplayiPhone55Inch: 220]
return heights[display]!
}()
}
| gpl-2.0 | 5030d5a74be789146f0633d4641046da | 28.184211 | 99 | 0.641118 | 4.366142 | false | false | false | false |
cruisediary/Diving | Diving/Models/Realm/RealmTravel.swift | 1 | 1516 | //
// Travel.swift
// Diving
//
// Created by CruzDiary on 5/24/16.
// Copyright © 2016 DigitalNomad. All rights reserved.
//
import RealmSwift
class RealmTravel: Object {
static let USERS:String = "users"
dynamic var id: String? = ""
dynamic var title: String? = nil
dynamic var startDate: NSDate? = nil
dynamic var endDate: NSDate? = nil
dynamic var createdAt: NSDate? = nil
//Relation
let users = List<RealmUser>()
//Key
override static func primaryKey() -> String? {
return RealmCommonObject.ID
}
static func newInstance(form: TravelCreateForm) -> RealmTravel {
let realmTravel = RealmTravel()
realmTravel.id = NSUUID().UUIDString
realmTravel.title = form.title
realmTravel.startDate = form.startDate
realmTravel.endDate = form.endDate
return realmTravel
}
static func create(travel: Travel) -> RealmTravel {
let realmTravel = RealmTravel()
realmTravel.id = NSUUID().UUIDString
realmTravel.title = travel.title
realmTravel.startDate = travel.startDate
realmTravel.endDate = travel.endDate
return realmTravel
}
func toStruct() -> Travel {
return Travel(id:id, title:title, startDate:startDate, endDate:endDate, createAt: createdAt)
}
// Specify properties to ignore (Realm won't persist these)
// override static func ignoredProperties() -> [String] {
// return []
// }
}
| mit | fbd92a6f74130cd67ed2cd59a70531c6 | 26.053571 | 100 | 0.634323 | 4.391304 | false | false | false | false |
jlecomte/EarthquakeTracker | EarthquakeTracker/Seismometer/SeismoViewController.swift | 1 | 4814 | //
// SeismoViewController.swift
// EarthquakeTracker
//
// Created by Andrew Folta on 10/11/14.
// Copyright (c) 2014 Andrew Folta. All rights reserved.
//
import UIKit
let SEISMO_DATA_COUNT = 100
let SEISMO_AXIS_SPACING = 0.2 // how often (in magnitude) to draw a grid line
let SEISMO_CANVAS_INSET = CGSize(width: 20.0, height: 8.0)
let SEISMO_NEEDLE_OFFSET = CGFloat(-12.5) // where the point is located within the needle image
let SEISMO_COLOR_FILL = UIColor(red: 252/255, green: 248/255, blue: 244/255, alpha: 1.0)
let SEISMO_COLOR_MINOR = UIColor(red: 246/255, green: 234/255, blue: 225/255, alpha: 1.0)
let SEISMO_COLOR_MAJOR = UIColor(red: 236/255, green: 219/255, blue: 201/255, alpha: 1.0)
// Many of these are just cached values so we don't have to recompute a lot.
@objc class SeismoDisplayData {
var values = RingBuffer(count: SEISMO_DATA_COUNT, repeatedValue: 0.0)
var xPixelsPerDatum = CGFloat() // number of x pixels per reading
var yPixelsPerMagnitude = CGFloat() // number of y pixels per unit of magnitude
var yScale = SEISMO_AXIS_SPACING // greatest magnitude (positive or negative) to show on the canvas
var yOrigin = CGFloat() // origin (zero point) of magnitude (i.e., half of canvas height)
}
class SeismoViewController: UIViewController, SeismoModelDelegate {
@IBOutlet weak var backgroundView: SeismoBackgroundView!
@IBOutlet weak var axisView: SeismoAxisView!
@IBOutlet weak var dataView: SeismoDataView!
@IBOutlet weak var needleView: UIImageView!
var seismoModel: SeismoModel?
var data = SeismoDisplayData()
func sizeUpdated() {
var canvas = view.bounds
canvas.origin.x += SEISMO_CANVAS_INSET.width
canvas.origin.y += SEISMO_CANVAS_INSET.height
canvas.size.width -= SEISMO_CANVAS_INSET.width
canvas.size.height -= 2.0 * SEISMO_CANVAS_INSET.height
backgroundView.frame = canvas
axisView.frame = canvas
dataView.frame = canvas
data.xPixelsPerDatum = canvas.size.width / CGFloat(SEISMO_DATA_COUNT)
data.yPixelsPerMagnitude = canvas.size.height / CGFloat(2.0 * data.yScale)
data.yOrigin = canvas.size.height / CGFloat(2.0)
backgroundView.sizeUpdated()
axisView.setNeedsDisplay()
dataView.setNeedsDisplay()
setNeedle()
}
func scaleUpdated() {
var canvas = backgroundView.frame
data.yPixelsPerMagnitude = canvas.size.height / CGFloat(2.0 * data.yScale)
backgroundView.scaleUpdated()
axisView.setNeedsDisplay()
dataView.setNeedsDisplay()
setNeedle()
}
func valuesUpdated() {
// update scale (if needed)
// (There are some clever things we can do by inspecting the newest value and the recently dropped value, but given the very spiky nature of our data we end up calculating the max most of the time anyway, so we'll just do that always.)
var m = self.data.values.reduce(0.0) { max($0, fabs($1)) }
var newScale = ceil(m / SEISMO_AXIS_SPACING) * SEISMO_AXIS_SPACING
newScale = max(newScale, SEISMO_AXIS_SPACING)
if self.data.yScale != newScale {
self.data.yScale = newScale
self.scaleUpdated()
}
backgroundView.valuesUpdated()
dataView.setNeedsDisplay()
setNeedle()
}
func setNeedle() {
var needleY = SEISMO_CANVAS_INSET.height + data.yOrigin + (CGFloat(data.values.newest) * data.yPixelsPerMagnitude)
needleView.frame.origin.y = needleY + SEISMO_NEEDLE_OFFSET
}
func reportNoAccelerometer() {
println("no accelerometer available")
}
func reportMagnitude(magnitude: Double) {
data.values.add(magnitude)
self.valuesUpdated()
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
super.willAnimateRotationToInterfaceOrientation(toInterfaceOrientation, duration: duration)
sizeUpdated()
}
override func viewDidLoad() {
super.viewDidLoad()
seismoModel = SeismoModel()
seismoModel?.delegate = self
// setup child views
backgroundView.data = data
axisView.data = data
dataView.data = data
// Oddly, we're in the wrong thread to do things like update the frames of child views.
dispatch_async(dispatch_get_main_queue(), {
self.sizeUpdated()
})
}
override func viewDidAppear(animated: Bool) {
seismoModel?.start()
}
override func viewWillDisappear(animated: Bool) {
seismoModel?.stop()
}
}
| mit | bd2b4d0ea9f2adf1f64b29b259d728e5 | 36.317829 | 243 | 0.654342 | 4.015013 | false | false | false | false |
WilliamIzzo83/journal | journal/code/controllers/TimelineViewController.swift | 1 | 14302 | //
// ViewController.swift
// journal
//
// Created by William Izzo on 11/01/2017.
// Copyright © 2017 wizzo. All rights reserved.
//
import UIKit
/**
Defines a view controller that is able to display the entries
*/
class TimelineViewController: UIViewController, InsertTextEntryViewControllerDelegate, UITableViewDataSource, UITableViewDelegate {
/**
View controller states. Also implements the logics
*/
enum States {
/// While in this state the controller did load
case ViewDidLoad
/// This state will load next journal data
case LoadNext
/// This state will load previous journal data
case LoadPrev
/// While in this state the controller will load timeline content on demand
case TraverseTimeline
/// User reached the first entry in history
case OldestTimelinePageLoaded
/// User reached the most recent day entry
case MostRecentTimelinePageLoaded
/// The timeline will set a transient page to let user edit a new day
case InsertTransientPage
/// The timeline will insert the newly created day entry
case InsertNewDayEntry
/**
* This state means there is an error somewhere with the DbEntry
*/
case Error
func checkTimelineBounds(last_inserted_index:Int, controller:TimelineViewController) {
if last_inserted_index == controller.timeline_provider.count() - 1 {
controller.setState(state: .InsertTransientPage)
}
if last_inserted_index == 0 {
controller.setState(state: .OldestTimelinePageLoaded)
return
}
controller.setState(state: .TraverseTimeline)
}
/**
This function is used to perform the logic associated with each state
- parameter controller: The controller receiving the state changes.
*/
func applyState(controller:TimelineViewController) -> Void{
switch self {
case .ViewDidLoad:
guard controller.timeline_provider.count() > 0 else {
controller.setState(state: .InsertTransientPage)
return
}
controller.selected_day_for_editing = nil
controller.pages_index_ref.insert(controller.current_timeline_index,
at: 0)
controller.journalTableView.reloadData()
controller.scrollToIndexPath(index_path: IndexPath(row: 0, section: 0))
checkTimelineBounds(last_inserted_index: controller.current_timeline_index, controller: controller)
break
case .LoadNext:
guard let last_index = controller.pages_index_ref.last else {
assert(false, "Missing last index")
return
}
defer {
checkTimelineBounds(last_inserted_index: last_index, controller: controller)
}
let journal_entries_count = controller.timeline_provider.count()
guard last_index < journal_entries_count - 1 && last_index != TimelineViewController.transient_day_page_index else {
return
}
//let rows_number = controller.pages_index_ref.count
controller.pages_index_ref.append(last_index + 1)
controller.journalTableView.reloadData()
break
case .LoadPrev:
guard let first_index = controller.pages_index_ref.first else {
assert(false, "Missing first index")
return
}
defer {
checkTimelineBounds(last_inserted_index: first_index, controller: controller)
}
guard first_index > 0 else {
return
}
let new_page_index = first_index - 1
let last_day_index = controller.timeline_provider.count() - 1
controller.pages_index_ref.insert(new_page_index, at: 0)
controller.journalTableView.reloadData()
let loaded_day = controller.timeline_provider.at(index: new_page_index)
let day_cell_size = computeTimelineCellHeight(
table_view: controller.journalTableView,
cell_archetype: controller.page_cell_archetype_,
day: loaded_day,
is_last_day: new_page_index == last_day_index,
is_transient_cell: false)
var current_table_offset = controller.journalTableView.contentOffset
current_table_offset.y = day_cell_size.height
controller.journalTableView.contentOffset = current_table_offset
break;
case .InsertTransientPage:
defer {
controller.setState(state: .MostRecentTimelinePageLoaded)
}
guard let last_index = controller.pages_index_ref.last else {
// There is no data, just append the transient cell index
// to refs.
controller.pages_index_ref.append(TimelineViewController.transient_day_page_index)
controller.journalTableView.reloadData()
return
}
guard last_index != -1 else {
// Transient cell already exists, so skip.
// TODO: call reload data so to update transient cell should
// current day change.
return
}
if controller.timeline_provider.entryAtDate(date: Date()) == nil {
controller.pages_index_ref.append(
TimelineViewController.transient_day_page_index)
controller.journalTableView.reloadData()
}
break
case .InsertNewDayEntry:
let last_index_ref_idx = controller.pages_index_ref.count - 1
let last_day_idx = controller.timeline_provider.count() - 1
controller.pages_index_ref[last_index_ref_idx] = last_day_idx
controller.journalTableView.reloadData()
controller.scrollToIndexPath(index_path: IndexPath(
row: last_index_ref_idx,
section: 0))
checkTimelineBounds(last_inserted_index: last_day_idx,
controller: controller)
break
case .TraverseTimeline:
controller.journalTableView.isHidden = false
break
default: // IMPROVEMENT: intercept the timeline end and do something
break
}
}
}
@IBOutlet weak var journalTableView: UITableView!
static private var transient_day_page_index = -1
var state : States!
var timeline_provider : EntriesDBTimelineReader!
var timeline_writer : EntriesDBTimelineWriter!
var dynamic_type_listener_ : NSObjectProtocol!
var significant_time_change_listener_ : NSObjectProtocol!
var selected_day_for_editing : DayDB?
var current_timeline_index : Int!
var pages_index_ref = [Int]()
var page_cell_archetype_ : JournalPageTableViewCell!
var selected_cell_ipath_ : IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
let page_cell_nib = UINib(nibName: "JournalPageTableViewCell", bundle: nil)
page_cell_archetype_ = page_cell_nib.instantiate(withOwner: nil, options: nil).first! as! JournalPageTableViewCell
journalTableView.dataSource = self
journalTableView.delegate = self
journalTableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 60.0, 0.0)
journalTableView.register(page_cell_nib, forCellReuseIdentifier: "page_cell")
dynamic_type_listener_ =
NotificationCenter.default.addObserver(
forName: NSNotification.Name.UIContentSizeCategoryDidChange,
object: nil,
queue: nil) { (note) in
self.view.setNeedsLayout()
}
significant_time_change_listener_ =
NotificationCenter.default.addObserver(
forName: Notification.Name.UIApplicationSignificantTimeChange,
object: nil,
queue: nil) { (note) in
self.setState(state: .LoadNext)
}
guard let entries_db = EntriesDB() else {
setState(state: .Error)
return
}
timeline_provider = entries_db.timelineReader()
timeline_writer = entries_db.timelineWriter()
current_timeline_index = timeline_provider.count() - 1
setState(state: .ViewDidLoad)
}
deinit {
NotificationCenter.default.removeObserver(dynamic_type_listener_)
NotificationCenter.default.removeObserver(significant_time_change_listener_)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func setState(state:States) {
self.state = state;
self.state.applyState(controller: self)
}
private func showInsertTextEntryController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let textEntryNC = storyboard.instantiateViewController(withIdentifier: "story_write_text_entry") as! UINavigationController
let textEntryVC = textEntryNC.viewControllers[0] as! InsertTextEntryViewController
textEntryVC.delegate = self
self.present(textEntryNC, animated: true, completion: nil)
}
func scrollToIndexPath(index_path:IndexPath) {
journalTableView.scrollToRow(at: index_path, at: .bottom, animated: false)
}
func didPressCancel(controller: InsertTextEntryViewController) {
self.dismiss(animated: true, completion: nil)
}
func didPressSave(controller: InsertTextEntryViewController, text:String) {
self.dismiss(animated: true, completion: nil)
if let day_to_edit = selected_day_for_editing {
guard timeline_writer.update_entry(text: text, day_entry: day_to_edit) else {
return
}
self.journalTableView.reloadData()
scrollToIndexPath(index_path: selected_cell_ipath_)
} else {
guard timeline_writer.write_entry(text: text, date: Date()) else {
// TODO: handle errors
return
}
setState(state: .InsertNewDayEntry)
}
}
func dayToEdit(controller: InsertTextEntryViewController) -> DayDB? {
return selected_day_for_editing
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0.0 && state != States.OldestTimelinePageLoaded {
self.setState(state: .LoadPrev)
return
}
if scrollView.contentSize.height - scrollView.contentOffset.y < scrollView.frame.size.height && state != States.MostRecentTimelinePageLoaded {
self.setState(state: .LoadNext)
return
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "page_cell", for: indexPath) as! JournalPageTableViewCell
let entries_count = timeline_provider.count()
let day_index = pages_index_ref[indexPath.row]
if day_index != TimelineViewController.transient_day_page_index {
let day = timeline_provider.at(index: day_index)
let is_last_day = day_index == entries_count - 1
timelineBindCellData(cell: cell,
day: day,
is_last_day: is_last_day)
} else {
timelineBindTransientCellData(cell: cell)
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let day_index = pages_index_ref[indexPath.row]
var day : DayDB?
let entries_count = timeline_provider.count()
let is_last_day = day_index == entries_count - 1
if (day_index >= 0) {
day = timeline_provider.at(index: day_index)
}
let size = computeTimelineCellHeight(
table_view: tableView,
cell_archetype: page_cell_archetype_,
day: day,
is_last_day: is_last_day,
is_transient_cell: day_index == TimelineViewController.transient_day_page_index)
return size.height
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pages_index_ref.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let day_index = pages_index_ref[indexPath.row]
selected_cell_ipath_ = indexPath
if day_index == TimelineViewController.transient_day_page_index {
selected_day_for_editing = nil
} else {
selected_day_for_editing = timeline_provider.at(index: day_index)
}
self.showInsertTextEntryController()
}
}
| bsd-3-clause | 8cf4b6ddce8318bfbbf5c95a202b6062 | 36.833333 | 151 | 0.561849 | 5.320313 | false | false | false | false |
codepgq/WeiBoDemo | PQWeiboDemo/PQWeiboDemo/classes/CenterAdd 添加/EmojiKeyBoard/EmoticonPackge.swift | 1 | 6219 | //
// Packges.swift
// EmojiKeyBoard
//
// Created by Mac on 16/10/26.
// Copyright © 2016年 Mac. All rights reserved.
//
import UIKit
class EmoticonPackge: NSObject {
private var id : String?
var group_name_cn : String?
var emoticons : [Emoticon]?
static let packgesList = loadPackges()
class func loadPackges() -> [EmoticonPackge]{
var packges = [EmoticonPackge]()
//加载最近组
packges.append(loadRecentEmoticon())
let path = (emoticonPath() as NSString).appendingPathComponent("emoticons.plist")
let packgesDict = NSDictionary(contentsOfFile: path)
for dict in packgesDict!["packages"] as! [[String : Any]] {
//获取地址
let packge = EmoticonPackge(id: dict["id"] as! String)
//添加组
packges.append(packge)
//获取文件路径
let subPath = packge.infoPath()
//加载表情数组
packge.loadEmoticon(path : subPath)
packge.loadEmptyEmotion()
}
return packges
}
//加载最近的表情
class func loadRecentEmoticon() -> EmoticonPackge{
let recent = EmoticonPackge(id : "")
recent.group_name_cn = "最近"
recent.emoticons = [Emoticon]()
recent.loadEmptyEmotion()
return recent
}
init(id : String) {
super.init()
self.id = id
}
// 用于添加最近表情
func appendRecentEmoticon(emoticon : Emoticon){
// 1.判断是否是删除按钮
if emoticon.isRemoveButton
{
return
}
// 2.判断当前点击的表情是否已经添加到最近数组中
let contains = emoticons!.contains(emoticon)
if !contains
{
// 删除删除按钮
emoticons?.removeLast()
emoticons?.append(emoticon)
}
// 3.对数组进行排序
var result = emoticons?.sorted(by: { (e1, e2) -> Bool in
return e1.times > e2.times
})
// 4.删除多余的表情
if !contains
{
result?.removeLast()
// 添加一个删除按钮
result?.append(Emoticon(remove: true))
}
emoticons = result
print(emoticons?.count ?? "表情为空")
}
//填充表情
private func loadEmptyEmotion(){
/*
每页显示21个表情,如果有多余的就填充
*/
let count = emoticons!.count % 21
//如果整除不了,就添加
for _ in count..<20 {
emoticons?.append(Emoticon(remove: false))
}
//最后一个添加删除按钮
emoticons?.append(Emoticon(remove: true))
}
//加载表情
private func loadEmoticon(path : String){
let dict = NSDictionary(contentsOfFile: path )!
group_name_cn = dict["group_name_cn"] as? String
emoticons = [Emoticon]()
var index = 0
for dict in dict["emoticons"] as! [[String : Any]] {
if index == 20 {
emoticons?.append(Emoticon(remove: true))
index = 0
}
emoticons?.append(Emoticon(dict : dict , id : id!))
index += 1
}
}
/// 根据表情文字找到对应的表情模型
///
/// - Parameter str: 字符串
/// - Returns: 表情模型
class func emoticonWithStr(str : String) -> Emoticon? {
var emoticon : Emoticon?
for packge in EmoticonPackge.loadPackges(){
emoticon = packge.emoticons?.filter({ (e) -> Bool in
if e.chs == nil{
return e.emojiStr == str
}
return e.chs == str
}).last
if emoticon != nil {
break
}
}
return emoticon
}
/// 查找表情字符串
///
/// - Parameter str: 字符串
/// - Returns: 属性字符串
class func attributeWithStr(str : String) -> NSMutableAttributedString? {
let mAttstr = NSMutableAttributedString(string: str)
do {
//1 创建规则
let pattern = "\\[.*?\\]"
//2 创建正则对象
let regex = try NSRegularExpression(pattern: pattern, options:.caseInsensitive)
//3 开始匹配
let res = regex.matches(in: str, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSRange(location: 0, length: str.characters.count))
//4 遍历对象 从后往前遍历
//4.1 找到最后一个的下标
var count = res.count
while count > 0 {
count -= 1
// 4.2 拿到对象
let checking : NSTextCheckingResult = res[count]
//4.3 拿到字符串
let temStr = (str as NSString).substring(with: checking.range)
//4.4 从模型去查找字符串
if let emoticon = emoticonWithStr(str: temStr){
//4.5 根据模型生存表情字符串
let att = EmoticonAttachment.imageText(emoticon: emoticon, font: UIFont.italicSystemFont(ofSize: 18))
//4.6 生成属性表情字符串
mAttstr.replaceCharacters(in: checking.range, with: att)
}
}
} catch{
print(error)
}
//5返回属性字符串
return mAttstr
}
//返回每个文件夹的plist文件
private func infoPath() -> String{
return ((EmoticonPackge.emoticonPath() as NSString).appendingPathComponent(id!) as NSString).appendingPathComponent("info.plist")
}
class func emoticonPath() -> String{
return (Bundle.main.bundlePath as NSString).appendingPathComponent("Emoticons.bundle")
}
}
| mit | 64ba530566d0aff052dc98d29f3c55bd | 26.658537 | 168 | 0.500529 | 4.572581 | false | false | false | false |
qiscus/qiscus-sdk-ios | Qiscus/Qiscus/View/QChatCell/QCellDeletedLeft.swift | 1 | 4235 | //
// QCellDeletedLeft.swift
// Qiscus
//
// Created by Ahmad Athaullah on 13/02/18.
// Copyright © 2018 Ahmad Athaullah. All rights reserved.
//
import UIKit
class QCellDeletedLeft: QChatCell {
let maxWidth:CGFloat = QiscusUIConfiguration.chatTextMaxWidth
let minWidth:CGFloat = 80
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var balloonView: UIImageView!
@IBOutlet weak var view: UIView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var balloonTopMargin: NSLayoutConstraint!
@IBOutlet weak var cellHeight: NSLayoutConstraint!
@IBOutlet weak var textViewWidth: NSLayoutConstraint!
@IBOutlet weak var textViewHeight: NSLayoutConstraint!
@IBOutlet weak var balloonWidth: NSLayoutConstraint!
@IBOutlet weak var textTopMargin: NSLayoutConstraint!
@IBOutlet weak var ballonHeight: NSLayoutConstraint!
@IBOutlet weak var balloonLeftMargin: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
textView.contentInset = UIEdgeInsets.zero
}
override func clearContext() {
textView.layoutIfNeeded()
}
@objc func openLink(){
self.delegate?.didTouchLink(onComment: self.comment!)
}
public override func commentChanged() {
if hideAvatar {
self.balloonLeftMargin.constant = 0
}else{
self.balloonLeftMargin.constant = 27
}
if let color = self.userNameColor {
self.userNameLabel.textColor = color
}
var deletedText = QChatCell.defaultDeletedText()
if let prefferedText = self.delegate?.deletedMessageText?(selfMessage: false){
deletedText = prefferedText
}
let attributedText = NSMutableAttributedString(string: deletedText)
let foregroundColorAttributeName = QiscusColorConfiguration.sharedInstance.leftBaloonTextColor
let textAttribute:[NSAttributedStringKey: Any] = [
NSAttributedStringKey.foregroundColor: foregroundColorAttributeName,
NSAttributedStringKey.font: Qiscus.style.chatFont.italic()
]
let allRange = (deletedText as NSString).range(of: deletedText)
attributedText.addAttributes(textAttribute, range: allRange)
self.balloonView.image = self.getBallon()
self.ballonHeight.constant = 10
self.textTopMargin.constant = 0
self.textView.attributedText = attributedText
let size = self.textView.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))
self.textViewWidth.constant = size.width
self.textViewHeight.constant = size.height
self.userNameLabel.textAlignment = .left
self.dateLabel.text = self.comment!.time.lowercased()
self.balloonView.tintColor = QiscusColorConfiguration.sharedInstance.leftBaloonColor
self.dateLabel.textColor = QiscusColorConfiguration.sharedInstance.leftBaloonTextColor
if self.showUserName{
if let sender = self.comment?.sender {
self.userNameLabel.text = sender.fullname
}else{
self.userNameLabel.text = self.comment?.senderName
}
self.userNameLabel.isHidden = false
self.balloonTopMargin.constant = 20
self.cellHeight.constant = 20
}else{
self.userNameLabel.text = ""
self.userNameLabel.isHidden = true
self.balloonTopMargin.constant = 0
self.cellHeight.constant = 0
}
self.textView.layoutIfNeeded()
}
public override func updateUserName() {
if let sender = self.comment?.sender {
self.userNameLabel.text = sender.fullname
}else{
self.userNameLabel.text = self.comment?.senderName
}
}
public override func comment(didChangePosition comment:QComment, position: QCellPosition) {
if comment.uniqueId == self.comment?.uniqueId {
self.balloonView.image = self.getBallon()
}
}
}
| mit | 0cec9e1aa6e4bf87e5667b68788f5494 | 34.579832 | 111 | 0.655881 | 5.233622 | false | false | false | false |
alickbass/ViewComponents | ViewComponentsTests/TestCALayerStyle.swift | 1 | 8587 | //
// TestCALayerStyle.swift
// ViewComponents
//
// Created by Oleksii on 04/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import XCTest
import ViewComponents
protocol ViewTestType {
associatedtype View
static var allStyles: [AnyStyle<View>] { get }
static var accumulatedHashes: [Int: Any] { get }
static var previousHashes: [Int: Any] { get }
func testAccumulatingHashes()
}
extension ViewTestType {
static var accumulatedHashes: [Int: Any] {
return allStyles.reduce(into: [:], { $0[$1.hashValue] = $1 })
}
func testAccumulatingHashes() {
var hashes = Self.previousHashes
for item in Self.allStyles {
let hash = item.hashValue
XCTAssertNil(hashes[hash], "\(item) has the same hash as \(hashes[hash]!)")
hashes[hash] = item
}
}
}
class TestCALayerStyle: XCTestCase, ViewTestType {
static let allStyles: [AnyStyle<CALayer>] = [
.contentsGravity(.bottom), AnyStyle<CALayer>.opacity(0.2), .isHidden(true), .masksToBounds(true),
.mask(CALayer()), .isDoubleSided(true), .backgroundColor(.red), .allowsEdgeAntialiasing(true),
.allowsGroupOpacity(true), .isOpaque(true), .edgeAntialiasingMask(.layerLeftEdge), .isGeometryFlipped(true),
.drawsAsynchronously(true), .shouldRasterize(true), .rasterizationScale(0.2), .contentsFormat(.RGBA16Float),
.frame(.zero), .bounds(.zero), .position(.zero), .zPosition(12),
.anchorPoint(.zero), .anchorPointZ(12), .contentsScale(0.2), .name("test"),
.mask(nil), .backgroundColor(nil), .name(nil)
]
static let previousHashes: [Int: Any] = [:]
func testCAGravity() {
XCTAssertEqual(CAGravity.center.rawValue, kCAGravityCenter)
XCTAssertEqual(CAGravity.top.rawValue, kCAGravityTop)
XCTAssertEqual(CAGravity.bottom.rawValue, kCAGravityBottom)
XCTAssertEqual(CAGravity.left.rawValue, kCAGravityLeft)
XCTAssertEqual(CAGravity.right.rawValue, kCAGravityRight)
XCTAssertEqual(CAGravity.topLeft.rawValue, kCAGravityTopLeft)
XCTAssertEqual(CAGravity.topRight.rawValue, kCAGravityTopRight)
XCTAssertEqual(CAGravity.bottomLeft.rawValue, kCAGravityBottomLeft)
XCTAssertEqual(CAGravity.bottomRight.rawValue, kCAGravityBottomRight)
XCTAssertEqual(CAGravity.resize.rawValue, kCAGravityResize)
XCTAssertEqual(CAGravity.resizeAspect.rawValue, kCAGravityResizeAspect)
XCTAssertEqual(CAGravity.resizeAspectFill.rawValue, kCAGravityResizeAspectFill)
XCTAssertEqual(CAGravity(rawValue: kCAGravityCenter), .center)
XCTAssertEqual(CAGravity(rawValue: kCAGravityTop), .top)
XCTAssertEqual(CAGravity(rawValue: kCAGravityBottom), .bottom)
XCTAssertEqual(CAGravity(rawValue: kCAGravityLeft), .left)
XCTAssertEqual(CAGravity(rawValue: kCAGravityRight), .right)
XCTAssertEqual(CAGravity(rawValue: kCAGravityTopLeft), .topLeft)
XCTAssertEqual(CAGravity(rawValue: kCAGravityTopRight), .topRight)
XCTAssertEqual(CAGravity(rawValue: kCAGravityBottomLeft), .bottomLeft)
XCTAssertEqual(CAGravity(rawValue: kCAGravityBottomRight), .bottomRight)
XCTAssertEqual(CAGravity(rawValue: kCAGravityResize), .resize)
XCTAssertEqual(CAGravity(rawValue: kCAGravityResizeAspect), .resizeAspect)
XCTAssertEqual(CAGravity(rawValue: kCAGravityResizeAspectFill), .resizeAspectFill)
XCTAssertNil(CAGravity(rawValue: "random"))
}
func testCAContentsFormat() {
XCTAssertEqual(CAContentsFormat.RGBA8Uint.rawValue, kCAContentsFormatRGBA8Uint)
XCTAssertEqual(CAContentsFormat.RGBA16Float.rawValue, kCAContentsFormatRGBA16Float)
XCTAssertEqual(CAContentsFormat.gray8Uint.rawValue, kCAContentsFormatGray8Uint)
XCTAssertEqual(CAContentsFormat(rawValue: kCAContentsFormatRGBA8Uint), .RGBA8Uint)
XCTAssertEqual(CAContentsFormat(rawValue: kCAContentsFormatRGBA16Float), .RGBA16Float)
XCTAssertEqual(CAContentsFormat(rawValue: kCAContentsFormatGray8Uint), .gray8Uint)
XCTAssertNil(CAContentsFormat(rawValue: "random"))
}
func testAnyStyleEquatable() {
XCTAssertEqual(AnyStyle<CALayer>.edgeAntialiasingMask(.layerLeftEdge), .edgeAntialiasingMask(.layerLeftEdge))
}
func testAnyStyleSideEffects() {
let view = CALayer()
view.contentsGravity = kCAGravityCenter
AnyStyle<CALayer>.contentsGravity(.bottom).sideEffect(on: view)
XCTAssertEqual(view.contentsGravity, kCAGravityBottom)
view.opacity = 1
AnyStyle<CALayer>.opacity(0.2).sideEffect(on: view)
XCTAssertEqual(view.opacity, 0.2)
view.isHidden = false
AnyStyle<CALayer>.isHidden(true).sideEffect(on: view)
XCTAssertEqual(view.isHidden, true)
view.masksToBounds = false
AnyStyle<CALayer>.masksToBounds(true).sideEffect(on: view)
XCTAssertEqual(view.masksToBounds, true)
let mask = CALayer()
view.mask = mask
AnyStyle<CALayer>.mask(mask).sideEffect(on: view)
XCTAssertEqual(view.mask, mask)
view.isDoubleSided = false
AnyStyle<CALayer>.isDoubleSided(true).sideEffect(on: view)
XCTAssertEqual(view.isDoubleSided, true)
view.backgroundColor = UIColor.red.cgColor
AnyStyle<CALayer>.backgroundColor(.green).sideEffect(on: view)
XCTAssertEqual(view.backgroundColor, UIColor.green.cgColor)
view.allowsEdgeAntialiasing = false
AnyStyle<CALayer>.allowsEdgeAntialiasing(true).sideEffect(on: view)
XCTAssertEqual(view.allowsEdgeAntialiasing, true)
view.allowsGroupOpacity = false
AnyStyle<CALayer>.allowsGroupOpacity(true).sideEffect(on: view)
XCTAssertEqual(view.allowsGroupOpacity, true)
view.isOpaque = false
AnyStyle<CALayer>.isOpaque(true).sideEffect(on: view)
XCTAssertEqual(view.isOpaque, true)
view.edgeAntialiasingMask = .layerTopEdge
AnyStyle<CALayer>.edgeAntialiasingMask(.layerLeftEdge).sideEffect(on: view)
XCTAssertEqual(view.edgeAntialiasingMask, .layerLeftEdge)
view.isGeometryFlipped = false
AnyStyle<CALayer>.isGeometryFlipped(true).sideEffect(on: view)
XCTAssertEqual(view.isGeometryFlipped, true)
view.drawsAsynchronously = false
AnyStyle<CALayer>.drawsAsynchronously(true).sideEffect(on: view)
XCTAssertEqual(view.drawsAsynchronously, true)
view.shouldRasterize = false
AnyStyle<CALayer>.shouldRasterize(true).sideEffect(on: view)
XCTAssertEqual(view.shouldRasterize, true)
view.rasterizationScale = 1
AnyStyle<CALayer>.rasterizationScale(0.2).sideEffect(on: view)
XCTAssertEqual(view.rasterizationScale, 0.2)
view.contentsFormat = kCAContentsFormatRGBA16Float
AnyStyle<CALayer>.contentsFormat(.RGBA8Uint).sideEffect(on: view)
XCTAssertEqual(view.contentsFormat, kCAContentsFormatRGBA8Uint)
view.frame = CGRect(x: 20, y: 20, width: 20, height: 20)
AnyStyle<CALayer>.frame(.zero).sideEffect(on: view)
XCTAssertEqual(view.frame, .zero)
view.bounds = CGRect(x: 20, y: 20, width: 20, height: 20)
AnyStyle<CALayer>.bounds(.zero).sideEffect(on: view)
XCTAssertEqual(view.bounds, .zero)
view.position = CGPoint(x: 20, y: 20)
AnyStyle<CALayer>.position(.zero).sideEffect(on: view)
XCTAssertEqual(view.position, .zero)
view.zPosition = 1
AnyStyle<CALayer>.zPosition(0.2).sideEffect(on: view)
XCTAssertEqual(view.zPosition, 0.2)
view.anchorPointZ = 1
AnyStyle<CALayer>.anchorPointZ(0.2).sideEffect(on: view)
XCTAssertEqual(view.anchorPointZ, 0.2)
view.anchorPoint = CGPoint(x: 0.5, y: 0.5)
AnyStyle<CALayer>.anchorPoint(.zero).sideEffect(on: view)
XCTAssertEqual(view.anchorPoint, .zero)
view.contentsScale = 1
AnyStyle<CALayer>.contentsScale(0.2).sideEffect(on: view)
XCTAssertEqual(view.contentsScale, 0.2)
view.name = nil
AnyStyle<CALayer>.name("test").sideEffect(on: view)
XCTAssertEqual(view.name, "test")
}
func testHashValue() {
testAccumulatingHashes()
}
}
| mit | 24aa42d2eca327d49cb7588ba15068e2 | 41.93 | 117 | 0.682506 | 4.389571 | false | true | false | false |
bolom/fastlane | fastlane/swift/ControlCommand.swift | 4 | 2196 | // ControlCommand.swift
// Copyright (c) 2021 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
struct ControlCommand: RubyCommandable {
static let commandKey = "command"
var type: CommandType { return .control }
enum ShutdownCommandType {
static let userMessageKey: String = "userMessage"
enum CancelReason {
static let reasonKey: String = "reason"
case clientError
case serverError
var reasonText: String {
switch self {
case .clientError:
return "clientError"
case .serverError:
return "serverError"
}
}
}
case done
case cancel(cancelReason: CancelReason)
var token: String {
switch self {
case .done:
return "done"
case .cancel:
return "cancelFastlaneRun"
}
}
}
let message: String?
let id: String = UUID().uuidString
let shutdownCommandType: ShutdownCommandType
var commandJson: String {
var jsonDictionary: [String: Any] = [ControlCommand.commandKey: shutdownCommandType.token]
if let message = message {
jsonDictionary[ShutdownCommandType.userMessageKey] = message
}
if case let .cancel(reason) = shutdownCommandType {
jsonDictionary[ShutdownCommandType.CancelReason.reasonKey] = reason.reasonText
}
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDictionary, options: [])
let jsonString = String(data: jsonData, encoding: .utf8)!
return jsonString
}
init(commandType: ShutdownCommandType, message: String? = nil) {
shutdownCommandType = commandType
self.message = message
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
| mit | 323443fb0d493d6615343988155d60c8 | 28.675676 | 98 | 0.612022 | 5.059908 | false | false | false | false |
cpmpercussion/microjam | Pods/DropDown/DropDown/src/DropDown.swift | 1 | 34544 | //
// DropDown.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
public typealias Index = Int
public typealias Closure = () -> Void
public typealias SelectionClosure = (Index, String) -> Void
public typealias MultiSelectionClosure = ([Index], [String]) -> Void
public typealias ConfigurationClosure = (Index, String) -> String
public typealias CellConfigurationClosure = (Index, String, DropDownCell) -> Void
private typealias ComputeLayoutTuple = (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat)
/// Can be `UIView` or `UIBarButtonItem`.
@objc
public protocol AnchorView: class {
var plainView: UIView { get }
}
extension UIView: AnchorView {
public var plainView: UIView {
return self
}
}
extension UIBarButtonItem: AnchorView {
public var plainView: UIView {
return value(forKey: "view") as! UIView
}
}
/// A Material Design drop down in replacement for `UIPickerView`.
public final class DropDown: UIView {
//TODO: handle iOS 7 landscape mode
/// The dismiss mode for a drop down.
public enum DismissMode {
/// A tap outside the drop down is required to dismiss.
case onTap
/// No tap is required to dismiss, it will dimiss when interacting with anything else.
case automatic
/// Not dismissable by the user.
case manual
}
/// The direction where the drop down will show from the `anchorView`.
public enum Direction {
/// The drop down will show below the anchor view when possible, otherwise above if there is more place than below.
case any
/// The drop down will show above the anchor view or will not be showed if not enough space.
case top
/// The drop down will show below or will not be showed if not enough space.
case bottom
}
//MARK: - Properties
/// The current visible drop down. There can be only one visible drop down at a time.
public static weak var VisibleDropDown: DropDown?
//MARK: UI
fileprivate let dismissableView = UIView()
fileprivate let tableViewContainer = UIView()
fileprivate let tableView = UITableView()
fileprivate var templateCell: DropDownCell!
fileprivate lazy var arrowIndication: UIImageView = {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 10), false, 0)
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 10))
path.addLine(to: CGPoint(x: 20, y: 10))
path.addLine(to: CGPoint(x: 10, y: 0))
path.addLine(to: CGPoint(x: 0, y: 10))
UIColor.black.setFill()
path.fill()
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let tintImg = img?.withRenderingMode(.alwaysTemplate)
let imgv = UIImageView(image: tintImg)
imgv.frame = CGRect(x: 0, y: -10, width: 15, height: 10)
return imgv
}()
/// The view to which the drop down will displayed onto.
public weak var anchorView: AnchorView? {
didSet { setNeedsUpdateConstraints() }
}
/**
The possible directions where the drop down will be showed.
See `Direction` enum for more info.
*/
public var direction = Direction.any
/**
The offset point relative to `anchorView` when the drop down is shown above the anchor view.
By default, the drop down is showed onto the `anchorView` with the top
left corner for its origin, so an offset equal to (0, 0).
You can change here the default drop down origin.
*/
public var topOffset: CGPoint = .zero {
didSet { setNeedsUpdateConstraints() }
}
/**
The offset point relative to `anchorView` when the drop down is shown below the anchor view.
By default, the drop down is showed onto the `anchorView` with the top
left corner for its origin, so an offset equal to (0, 0).
You can change here the default drop down origin.
*/
public var bottomOffset: CGPoint = .zero {
didSet { setNeedsUpdateConstraints() }
}
/**
The offset from the bottom of the window when the drop down is shown below the anchor view.
DropDown applies this offset only if keyboard is hidden.
*/
public var offsetFromWindowBottom = CGFloat(0) {
didSet { setNeedsUpdateConstraints() }
}
/**
The width of the drop down.
Defaults to `anchorView.bounds.width - offset.x`.
*/
public var width: CGFloat? {
didSet { setNeedsUpdateConstraints() }
}
/**
arrowIndication.x
arrowIndication will be add to tableViewContainer when configured
*/
public var arrowIndicationX: CGFloat? {
didSet {
if let arrowIndicationX = arrowIndicationX {
tableViewContainer.addSubview(arrowIndication)
arrowIndication.tintColor = tableViewBackgroundColor
arrowIndication.frame.origin.x = arrowIndicationX
} else {
arrowIndication.removeFromSuperview()
}
}
}
//MARK: Constraints
fileprivate var heightConstraint: NSLayoutConstraint!
fileprivate var widthConstraint: NSLayoutConstraint!
fileprivate var xConstraint: NSLayoutConstraint!
fileprivate var yConstraint: NSLayoutConstraint!
//MARK: Appearance
@objc public dynamic var cellHeight = DPDConstant.UI.RowHeight {
willSet { tableView.rowHeight = newValue }
didSet { reloadAllComponents() }
}
@objc fileprivate dynamic var tableViewBackgroundColor = DPDConstant.UI.BackgroundColor {
willSet {
tableView.backgroundColor = newValue
if arrowIndicationX != nil { arrowIndication.tintColor = newValue }
}
}
public override var backgroundColor: UIColor? {
get { return tableViewBackgroundColor }
set { tableViewBackgroundColor = newValue! }
}
/**
The color of the dimmed background (behind the drop down, covering the entire screen).
*/
public var dimmedBackgroundColor = UIColor.clear {
willSet { super.backgroundColor = newValue }
}
/**
The background color of the selected cell in the drop down.
Changing the background color automatically reloads the drop down.
*/
@objc public dynamic var selectionBackgroundColor = DPDConstant.UI.SelectionBackgroundColor
/**
The separator color between cells.
Changing the separator color automatically reloads the drop down.
*/
@objc public dynamic var separatorColor = DPDConstant.UI.SeparatorColor {
willSet { tableView.separatorColor = newValue }
didSet { reloadAllComponents() }
}
/**
The corner radius of DropDown.
Changing the corner radius automatically reloads the drop down.
*/
@objc public dynamic var cornerRadius = DPDConstant.UI.CornerRadius {
willSet {
tableViewContainer.layer.cornerRadius = newValue
tableView.layer.cornerRadius = newValue
}
didSet { reloadAllComponents() }
}
/**
Alias method for `cornerRadius` variable to avoid ambiguity.
*/
@objc public dynamic func setupCornerRadius(_ radius: CGFloat) {
tableViewContainer.layer.cornerRadius = radius
tableView.layer.cornerRadius = radius
reloadAllComponents()
}
/**
The masked corners of DropDown.
Changing the masked corners automatically reloads the drop down.
*/
@available(iOS 11.0, *)
@objc public dynamic func setupMaskedCorners(_ cornerMask: CACornerMask) {
tableViewContainer.layer.maskedCorners = cornerMask
tableView.layer.maskedCorners = cornerMask
reloadAllComponents()
}
/**
The color of the shadow.
Changing the shadow color automatically reloads the drop down.
*/
@objc public dynamic var shadowColor = DPDConstant.UI.Shadow.Color {
willSet { tableViewContainer.layer.shadowColor = newValue.cgColor }
didSet { reloadAllComponents() }
}
/**
The offset of the shadow.
Changing the shadow color automatically reloads the drop down.
*/
@objc public dynamic var shadowOffset = DPDConstant.UI.Shadow.Offset {
willSet { tableViewContainer.layer.shadowOffset = newValue }
didSet { reloadAllComponents() }
}
/**
The opacity of the shadow.
Changing the shadow opacity automatically reloads the drop down.
*/
@objc public dynamic var shadowOpacity = DPDConstant.UI.Shadow.Opacity {
willSet { tableViewContainer.layer.shadowOpacity = newValue }
didSet { reloadAllComponents() }
}
/**
The radius of the shadow.
Changing the shadow radius automatically reloads the drop down.
*/
@objc public dynamic var shadowRadius = DPDConstant.UI.Shadow.Radius {
willSet { tableViewContainer.layer.shadowRadius = newValue }
didSet { reloadAllComponents() }
}
/**
The duration of the show/hide animation.
*/
@objc public dynamic var animationduration = DPDConstant.Animation.Duration
/**
The option of the show animation. Global change.
*/
public static var animationEntranceOptions = DPDConstant.Animation.EntranceOptions
/**
The option of the hide animation. Global change.
*/
public static var animationExitOptions = DPDConstant.Animation.ExitOptions
/**
The option of the show animation. Only change the caller. To change all drop down's use the static var.
*/
public var animationEntranceOptions: UIView.AnimationOptions = DropDown.animationEntranceOptions
/**
The option of the hide animation. Only change the caller. To change all drop down's use the static var.
*/
public var animationExitOptions: UIView.AnimationOptions = DropDown.animationExitOptions
/**
The downScale transformation of the tableview when the DropDown is appearing
*/
public var downScaleTransform = DPDConstant.Animation.DownScaleTransform {
willSet { tableViewContainer.transform = newValue }
}
/**
The color of the text for each cells of the drop down.
Changing the text color automatically reloads the drop down.
*/
@objc public dynamic var textColor = DPDConstant.UI.TextColor {
didSet { reloadAllComponents() }
}
/**
The color of the text for selected cells of the drop down.
Changing the text color automatically reloads the drop down.
*/
@objc public dynamic var selectedTextColor = DPDConstant.UI.SelectedTextColor {
didSet { reloadAllComponents() }
}
/**
The font of the text for each cells of the drop down.
Changing the text font automatically reloads the drop down.
*/
@objc public dynamic var textFont = DPDConstant.UI.TextFont {
didSet { reloadAllComponents() }
}
/**
The NIB to use for DropDownCells
Changing the cell nib automatically reloads the drop down.
*/
public var cellNib = UINib(nibName: "DropDownCell", bundle: Bundle(for: DropDownCell.self)) {
didSet {
tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell)
templateCell = nil
reloadAllComponents()
}
}
//MARK: Content
/**
The data source for the drop down.
Changing the data source automatically reloads the drop down.
*/
public var dataSource = [String]() {
didSet {
deselectRows(at: selectedRowIndices)
reloadAllComponents()
}
}
/**
The localization keys for the data source for the drop down.
Changing this value automatically reloads the drop down.
This has uses for setting accibility identifiers on the drop down cells (same ones as the localization keys).
*/
public var localizationKeysDataSource = [String]() {
didSet {
dataSource = localizationKeysDataSource.map { NSLocalizedString($0, comment: "") }
}
}
/// The indicies that have been selected
fileprivate var selectedRowIndices = Set<Index>()
/**
The format for the cells' text.
By default, the cell's text takes the plain `dataSource` value.
Changing `cellConfiguration` automatically reloads the drop down.
*/
public var cellConfiguration: ConfigurationClosure? {
didSet { reloadAllComponents() }
}
/**
A advanced formatter for the cells. Allows customization when custom cells are used
Changing `customCellConfiguration` automatically reloads the drop down.
*/
public var customCellConfiguration: CellConfigurationClosure? {
didSet { reloadAllComponents() }
}
/// The action to execute when the user selects a cell.
public var selectionAction: SelectionClosure?
/**
The action to execute when the user selects multiple cells.
Providing an action will turn on multiselection mode.
The single selection action will still be called if provided.
*/
public var multiSelectionAction: MultiSelectionClosure?
/// The action to execute when the drop down will show.
public var willShowAction: Closure?
/// The action to execute when the user cancels/hides the drop down.
public var cancelAction: Closure?
/// The dismiss mode of the drop down. Default is `OnTap`.
public var dismissMode = DismissMode.onTap {
willSet {
if newValue == .onTap {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissableViewTapped))
dismissableView.addGestureRecognizer(gestureRecognizer)
} else if let gestureRecognizer = dismissableView.gestureRecognizers?.first {
dismissableView.removeGestureRecognizer(gestureRecognizer)
}
}
}
fileprivate var minHeight: CGFloat {
return tableView.rowHeight
}
fileprivate var didSetupConstraints = false
//MARK: - Init's
deinit {
stopListeningToNotifications()
}
/**
Creates a new instance of a drop down.
Don't forget to setup the `dataSource`,
the `anchorView` and the `selectionAction`
at least before calling `show()`.
*/
public convenience init() {
self.init(frame: .zero)
}
/**
Creates a new instance of a drop down.
- parameter anchorView: The view to which the drop down will displayed onto.
- parameter selectionAction: The action to execute when the user selects a cell.
- parameter dataSource: The data source for the drop down.
- parameter topOffset: The offset point relative to `anchorView` used when drop down is displayed on above the anchor view.
- parameter bottomOffset: The offset point relative to `anchorView` used when drop down is displayed on below the anchor view.
- parameter cellConfiguration: The format for the cells' text.
- parameter cancelAction: The action to execute when the user cancels/hides the drop down.
- returns: A new instance of a drop down customized with the above parameters.
*/
public convenience init(anchorView: AnchorView, selectionAction: SelectionClosure? = nil, dataSource: [String] = [], topOffset: CGPoint? = nil, bottomOffset: CGPoint? = nil, cellConfiguration: ConfigurationClosure? = nil, cancelAction: Closure? = nil) {
self.init(frame: .zero)
self.anchorView = anchorView
self.selectionAction = selectionAction
self.dataSource = dataSource
self.topOffset = topOffset ?? .zero
self.bottomOffset = bottomOffset ?? .zero
self.cellConfiguration = cellConfiguration
self.cancelAction = cancelAction
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
//MARK: - Setup
private extension DropDown {
func setup() {
tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell)
DispatchQueue.main.async {
//HACK: If not done in dispatch_async on main queue `setupUI` will have no effect
self.updateConstraintsIfNeeded()
self.setupUI()
}
tableView.rowHeight = cellHeight
setHiddentState()
isHidden = true
dismissMode = .onTap
tableView.delegate = self
tableView.dataSource = self
startListeningToKeyboard()
accessibilityIdentifier = "drop_down"
}
func setupUI() {
super.backgroundColor = dimmedBackgroundColor
tableViewContainer.layer.masksToBounds = false
tableViewContainer.layer.cornerRadius = cornerRadius
tableViewContainer.layer.shadowColor = shadowColor.cgColor
tableViewContainer.layer.shadowOffset = shadowOffset
tableViewContainer.layer.shadowOpacity = shadowOpacity
tableViewContainer.layer.shadowRadius = shadowRadius
tableView.backgroundColor = tableViewBackgroundColor
tableView.separatorColor = separatorColor
tableView.layer.cornerRadius = cornerRadius
tableView.layer.masksToBounds = true
}
}
//MARK: - UI
extension DropDown {
public override func updateConstraints() {
if !didSetupConstraints {
setupConstraints()
}
didSetupConstraints = true
let layout = computeLayout()
if !layout.canBeDisplayed {
super.updateConstraints()
hide()
return
}
xConstraint.constant = layout.x
yConstraint.constant = layout.y
widthConstraint.constant = layout.width
heightConstraint.constant = layout.visibleHeight
tableView.isScrollEnabled = layout.offscreenHeight > 0
DispatchQueue.main.async { [weak self] in
self?.tableView.flashScrollIndicators()
}
super.updateConstraints()
}
fileprivate func setupConstraints() {
translatesAutoresizingMaskIntoConstraints = false
// Dismissable view
addSubview(dismissableView)
dismissableView.translatesAutoresizingMaskIntoConstraints = false
addUniversalConstraints(format: "|[dismissableView]|", views: ["dismissableView": dismissableView])
// Table view container
addSubview(tableViewContainer)
tableViewContainer.translatesAutoresizingMaskIntoConstraints = false
xConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 0)
addConstraint(xConstraint)
yConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 0)
addConstraint(yConstraint)
widthConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0)
tableViewContainer.addConstraint(widthConstraint)
heightConstraint = NSLayoutConstraint(
item: tableViewContainer,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0)
tableViewContainer.addConstraint(heightConstraint)
// Table view
tableViewContainer.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableViewContainer.addUniversalConstraints(format: "|[tableView]|", views: ["tableView": tableView])
}
public override func layoutSubviews() {
super.layoutSubviews()
// When orientation changes, layoutSubviews is called
// We update the constraint to update the position
setNeedsUpdateConstraints()
let shadowPath = UIBezierPath(roundedRect: tableViewContainer.bounds, cornerRadius: cornerRadius)
tableViewContainer.layer.shadowPath = shadowPath.cgPath
}
fileprivate func computeLayout() -> (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat, visibleHeight: CGFloat, canBeDisplayed: Bool, Direction: Direction) {
var layout: ComputeLayoutTuple = (0, 0, 0, 0)
var direction = self.direction
guard let window = UIWindow.visibleWindow() else { return (0, 0, 0, 0, 0, false, direction) }
barButtonItemCondition: if let anchorView = anchorView as? UIBarButtonItem {
let isRightBarButtonItem = anchorView.plainView.frame.minX > window.frame.midX
guard isRightBarButtonItem else { break barButtonItemCondition }
let width = self.width ?? fittingWidth()
let anchorViewWidth = anchorView.plainView.frame.width
let x = -(width - anchorViewWidth)
bottomOffset = CGPoint(x: x, y: 0)
}
if anchorView == nil {
layout = computeLayoutBottomDisplay(window: window)
direction = .any
} else {
switch direction {
case .any:
layout = computeLayoutBottomDisplay(window: window)
direction = .bottom
if layout.offscreenHeight > 0 {
let topLayout = computeLayoutForTopDisplay(window: window)
if topLayout.offscreenHeight < layout.offscreenHeight {
layout = topLayout
direction = .top
}
}
case .bottom:
layout = computeLayoutBottomDisplay(window: window)
direction = .bottom
case .top:
layout = computeLayoutForTopDisplay(window: window)
direction = .top
}
}
constraintWidthToFittingSizeIfNecessary(layout: &layout)
constraintWidthToBoundsIfNecessary(layout: &layout, in: window)
let visibleHeight = tableHeight - layout.offscreenHeight
let canBeDisplayed = visibleHeight >= minHeight
return (layout.x, layout.y, layout.width, layout.offscreenHeight, visibleHeight, canBeDisplayed, direction)
}
fileprivate func computeLayoutBottomDisplay(window: UIWindow) -> ComputeLayoutTuple {
var offscreenHeight: CGFloat = 0
let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - bottomOffset.x
let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? window.frame.midX - (width / 2)
let anchorViewY = anchorView?.plainView.windowFrame?.minY ?? window.frame.midY - (tableHeight / 2)
let x = anchorViewX + bottomOffset.x
let y = anchorViewY + bottomOffset.y
let maxY = y + tableHeight
let windowMaxY = window.bounds.maxY - DPDConstant.UI.HeightPadding - offsetFromWindowBottom
let keyboardListener = KeyboardListener.sharedInstance
let keyboardMinY = keyboardListener.keyboardFrame.minY - DPDConstant.UI.HeightPadding
if keyboardListener.isVisible && maxY > keyboardMinY {
offscreenHeight = abs(maxY - keyboardMinY)
} else if maxY > windowMaxY {
offscreenHeight = abs(maxY - windowMaxY)
}
return (x, y, width, offscreenHeight)
}
fileprivate func computeLayoutForTopDisplay(window: UIWindow) -> ComputeLayoutTuple {
var offscreenHeight: CGFloat = 0
let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? 0
let anchorViewMaxY = anchorView?.plainView.windowFrame?.maxY ?? 0
let x = anchorViewX + topOffset.x
var y = (anchorViewMaxY + topOffset.y) - tableHeight
let windowY = window.bounds.minY + DPDConstant.UI.HeightPadding
if y < windowY {
offscreenHeight = abs(y - windowY)
y = windowY
}
let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - topOffset.x
return (x, y, width, offscreenHeight)
}
fileprivate func fittingWidth() -> CGFloat {
if templateCell == nil {
templateCell = (cellNib.instantiate(withOwner: nil, options: nil)[0] as! DropDownCell)
}
var maxWidth: CGFloat = 0
for index in 0..<dataSource.count {
configureCell(templateCell, at: index)
templateCell.bounds.size.height = cellHeight
let width = templateCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width
if width > maxWidth {
maxWidth = width
}
}
return maxWidth
}
fileprivate func constraintWidthToBoundsIfNecessary(layout: inout ComputeLayoutTuple, in window: UIWindow) {
let windowMaxX = window.bounds.maxX
let maxX = layout.x + layout.width
if maxX > windowMaxX {
let delta = maxX - windowMaxX
let newOrigin = layout.x - delta
if newOrigin > 0 {
layout.x = newOrigin
} else {
layout.x = 0
layout.width += newOrigin // newOrigin is negative, so this operation is a substraction
}
}
}
fileprivate func constraintWidthToFittingSizeIfNecessary(layout: inout ComputeLayoutTuple) {
guard width == nil else { return }
if layout.width < fittingWidth() {
layout.width = fittingWidth()
}
}
}
//MARK: - Actions
extension DropDown {
/**
An Objective-C alias for the show() method which converts the returned tuple into an NSDictionary.
- returns: An NSDictionary with a value for the "canBeDisplayed" Bool, and possibly for the "offScreenHeight" Optional(CGFloat).
*/
@objc(show)
public func objc_show() -> NSDictionary {
let (canBeDisplayed, offScreenHeight) = show()
var info = [AnyHashable: Any]()
info["canBeDisplayed"] = canBeDisplayed
if let offScreenHeight = offScreenHeight {
info["offScreenHeight"] = offScreenHeight
}
return NSDictionary(dictionary: info)
}
/**
Shows the drop down if enough height.
- returns: Wether it succeed and how much height is needed to display all cells at once.
*/
@discardableResult
public func show(onTopOf window: UIWindow? = nil, beforeTransform transform: CGAffineTransform? = nil, anchorPoint: CGPoint? = nil) -> (canBeDisplayed: Bool, offscreenHeight: CGFloat?) {
if self == DropDown.VisibleDropDown && DropDown.VisibleDropDown?.isHidden == false { // added condition - DropDown.VisibleDropDown?.isHidden == false -> to resolve forever hiding dropdown issue when continuous taping on button - Kartik Patel - 2016-12-29
return (true, 0)
}
if let visibleDropDown = DropDown.VisibleDropDown {
visibleDropDown.cancel()
}
willShowAction?()
DropDown.VisibleDropDown = self
setNeedsUpdateConstraints()
let visibleWindow = window != nil ? window : UIWindow.visibleWindow()
visibleWindow?.addSubview(self)
visibleWindow?.bringSubviewToFront(self)
self.translatesAutoresizingMaskIntoConstraints = false
visibleWindow?.addUniversalConstraints(format: "|[dropDown]|", views: ["dropDown": self])
let layout = computeLayout()
if !layout.canBeDisplayed {
hide()
return (layout.canBeDisplayed, layout.offscreenHeight)
}
isHidden = false
if anchorPoint != nil {
tableViewContainer.layer.anchorPoint = anchorPoint!
}
if transform != nil {
tableViewContainer.transform = transform!
} else {
tableViewContainer.transform = downScaleTransform
}
layoutIfNeeded()
UIView.animate(
withDuration: animationduration,
delay: 0,
options: animationEntranceOptions,
animations: { [weak self] in
self?.setShowedState()
},
completion: nil)
accessibilityViewIsModal = true
UIAccessibility.post(notification: .screenChanged, argument: self)
//deselectRows(at: selectedRowIndices)
selectRows(at: selectedRowIndices)
return (layout.canBeDisplayed, layout.offscreenHeight)
}
public override func accessibilityPerformEscape() -> Bool {
switch dismissMode {
case .automatic, .onTap:
cancel()
return true
case .manual:
return false
}
}
/// Hides the drop down.
public func hide() {
if self == DropDown.VisibleDropDown {
/*
If one drop down is showed and another one is not
but we call `hide()` on the hidden one:
we don't want it to set the `VisibleDropDown` to nil.
*/
DropDown.VisibleDropDown = nil
}
if isHidden {
return
}
UIView.animate(
withDuration: animationduration,
delay: 0,
options: animationExitOptions,
animations: { [weak self] in
self?.setHiddentState()
},
completion: { [weak self] finished in
guard let `self` = self else { return }
self.isHidden = true
self.removeFromSuperview()
UIAccessibility.post(notification: .screenChanged, argument: nil)
})
}
fileprivate func cancel() {
hide()
cancelAction?()
}
fileprivate func setHiddentState() {
alpha = 0
}
fileprivate func setShowedState() {
alpha = 1
tableViewContainer.transform = CGAffineTransform.identity
}
}
//MARK: - UITableView
extension DropDown {
/**
Reloads all the cells.
It should not be necessary in most cases because each change to
`dataSource`, `textColor`, `textFont`, `selectionBackgroundColor`
and `cellConfiguration` implicitly calls `reloadAllComponents()`.
*/
public func reloadAllComponents() {
DispatchQueue.executeOnMainThread {
self.tableView.reloadData()
self.setNeedsUpdateConstraints()
}
}
/// (Pre)selects a row at a certain index.
public func selectRow(at index: Index?, scrollPosition: UITableView.ScrollPosition = .none) {
if let index = index {
tableView.selectRow(
at: IndexPath(row: index, section: 0), animated: true, scrollPosition: scrollPosition
)
selectedRowIndices.insert(index)
} else {
deselectRows(at: selectedRowIndices)
selectedRowIndices.removeAll()
}
}
public func selectRows(at indices: Set<Index>?) {
indices?.forEach {
selectRow(at: $0)
}
// if we are in multi selection mode then reload data so that all selections are shown
if multiSelectionAction != nil {
tableView.reloadData()
}
}
public func deselectRow(at index: Index?) {
guard let index = index
, index >= 0
else { return }
// remove from indices
if let selectedRowIndex = selectedRowIndices.index(where: { $0 == index }) {
selectedRowIndices.remove(at: selectedRowIndex)
}
tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: true)
}
// de-selects the rows at the indices provided
public func deselectRows(at indices: Set<Index>?) {
indices?.forEach {
deselectRow(at: $0)
}
}
/// Returns the index of the selected row.
public var indexForSelectedRow: Index? {
return (tableView.indexPathForSelectedRow as NSIndexPath?)?.row
}
/// Returns the selected item.
public var selectedItem: String? {
guard let row = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row else { return nil }
return dataSource[row]
}
/// Returns the height needed to display all cells.
fileprivate var tableHeight: CGFloat {
return tableView.rowHeight * CGFloat(dataSource.count)
}
//MARK: Objective-C methods for converting the Swift type Index
@objc public func selectRow(_ index: Int, scrollPosition: UITableView.ScrollPosition = .none) {
self.selectRow(at:Index(index), scrollPosition: scrollPosition)
}
@objc public func clearSelection() {
self.selectRow(at:nil)
}
@objc public func deselectRow(_ index: Int) {
tableView.deselectRow(at: IndexPath(row: Index(index), section: 0), animated: true)
}
@objc public var indexPathForSelectedRow: NSIndexPath? {
return tableView.indexPathForSelectedRow as NSIndexPath?
}
}
//MARK: - UITableViewDataSource - UITableViewDelegate
extension DropDown: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DPDConstant.ReusableIdentifier.DropDownCell, for: indexPath) as! DropDownCell
let index = (indexPath as NSIndexPath).row
configureCell(cell, at: index)
return cell
}
fileprivate func configureCell(_ cell: DropDownCell, at index: Int) {
if index >= 0 && index < localizationKeysDataSource.count {
cell.accessibilityIdentifier = localizationKeysDataSource[index]
}
cell.optionLabel.textColor = textColor
cell.optionLabel.font = textFont
cell.selectedBackgroundColor = selectionBackgroundColor
cell.highlightTextColor = selectedTextColor
cell.normalTextColor = textColor
if let cellConfiguration = cellConfiguration {
cell.optionLabel.text = cellConfiguration(index, dataSource[index])
} else {
cell.optionLabel.text = dataSource[index]
}
customCellConfiguration?(index, dataSource[index], cell)
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.isSelected = selectedRowIndices.first{ $0 == (indexPath as NSIndexPath).row } != nil
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedRowIndex = (indexPath as NSIndexPath).row
// are we in multi-selection mode?
if let multiSelectionCallback = multiSelectionAction {
// if already selected then deselect
if selectedRowIndices.first(where: { $0 == selectedRowIndex}) != nil {
deselectRow(at: selectedRowIndex)
let selectedRowIndicesArray = Array(selectedRowIndices)
let selectedRows = selectedRowIndicesArray.map { dataSource[$0] }
multiSelectionCallback(selectedRowIndicesArray, selectedRows)
return
}
else {
selectedRowIndices.insert(selectedRowIndex)
let selectedRowIndicesArray = Array(selectedRowIndices)
let selectedRows = selectedRowIndicesArray.map { dataSource[$0] }
selectionAction?(selectedRowIndex, dataSource[selectedRowIndex])
multiSelectionCallback(selectedRowIndicesArray, selectedRows)
tableView.reloadData()
return
}
}
// Perform single selection logic
selectedRowIndices.removeAll()
selectedRowIndices.insert(selectedRowIndex)
selectionAction?(selectedRowIndex, dataSource[selectedRowIndex])
if let _ = anchorView as? UIBarButtonItem {
// DropDown's from UIBarButtonItem are menus so we deselect the selected menu right after selection
deselectRow(at: selectedRowIndex)
}
hide()
}
}
//MARK: - Auto dismiss
extension DropDown {
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if dismissMode == .automatic && view === dismissableView {
cancel()
return nil
} else {
return view
}
}
@objc
fileprivate func dismissableViewTapped() {
cancel()
}
}
//MARK: - Keyboard events
extension DropDown {
/**
Starts listening to keyboard events.
Allows the drop down to display correctly when keyboard is showed.
*/
@objc public static func startListeningToKeyboard() {
KeyboardListener.sharedInstance.startListeningToKeyboard()
}
fileprivate func startListeningToKeyboard() {
KeyboardListener.sharedInstance.startListeningToKeyboard()
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardUpdate),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardUpdate),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
fileprivate func stopListeningToNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc
fileprivate func keyboardUpdate() {
self.setNeedsUpdateConstraints()
}
}
private extension DispatchQueue {
static func executeOnMainThread(_ closure: @escaping Closure) {
if Thread.isMainThread {
closure()
} else {
main.async(execute: closure)
}
}
}
| mit | d8cf0d169980d334e382763b3b994b3c | 27.882943 | 256 | 0.71833 | 4.409497 | false | false | false | false |
wanliming11/MurlocAlgorithms | Last/LeetCode/String/67._Add_Binary/67. Add Binary/main.swift | 1 | 3097 | //
// main.swift
// 67. Add Binary
//
// Created by FlyingPuPu on 04/02/2017.
// Copyright (c) 2017 FPP. All rights reserved.
//
import Foundation
/*
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
/*
Thinking:
由于是计算和,那么最多的长度也只是 a, b 最大长度 +1
先把a, b 转换为整形,然后通过余数和商来计算进位,
根据计算结果和进位,来判断放入到字符串数组里面的值。
//Error1: 如果转换为整型,则很容易出现数值过大越界的情况
*/
func addBinary(_ a: String, _ b: String) -> String {
guard a.lengthOfBytes(using: .ascii) > 0, b.lengthOfBytes(using: .ascii) > 0 else {
return ""
}
/*
根据位数计算进位与和
*/
func calc(_ lhs: Character, _ rhs: Character, _ carry: Bool) -> (String, Bool) {
switch (lhs, rhs, carry) {
case ("1", "1", false), ("0", "1", true), ("1", "0", true):
return ("0", true)
case ("1", "1", true):
return ("1", true)
case ("0", "1", false), ("1", "0", false), ("0", "0", true):
return ("1", false)
case ("0", "0", false):
return ("0", false)
default:
return ("0", false)
}
}
//如果为负数了,直接拿到的是0
func character(at index: Int, _ charactersArray: String) -> Character {
guard index >= 0, index < charactersArray.characters.count else {
return "0"
}
return charactersArray.characters[charactersArray.index(charactersArray.startIndex, offsetBy: index)]
}
let aLength = a.lengthOfBytes(using: .ascii)
let bLength = b.lengthOfBytes(using: .ascii)
var lIndex = aLength - 1, rIndex = bLength - 1
var lRemainder: Character = "0", rRmainder: Character = "0" //余数
var carry = false //是否产生进位
let maxLength = max(aLength, bLength) + 1
var charactersArray = Array<Character>(repeating: "0", count: maxLength)
var step = maxLength - 1
while step != 0 {
let result: String
lRemainder = character(at: lIndex, a)
rRmainder = character(at: rIndex, b)
(result, carry) = calc(lRemainder, rRmainder, carry)
charactersArray[step] = Character(String(result))
lIndex -= 1
rIndex -= 1
step -= 1
}
if carry, step >= 0 {
charactersArray[step] = "1"
}
print(charactersArray)
//去掉前面多余的零
var dropIndex = 0
for (index, value) in charactersArray.enumerated() {
dropIndex = index
if value == "1" {
break
}
}
print(dropIndex)
charactersArray = Array<Character>(charactersArray.dropFirst(dropIndex))
print(charactersArray)
return String(charactersArray)
}
print(addBinary("10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101",
"110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"))
| mit | bc0fceb1c9bbda1dc5532ed062acb47c | 27.37 | 114 | 0.604512 | 3.418072 | false | false | false | false |
dautermann/NestLogin | NestLogin/AuthorizationViewController.swift | 1 | 5862 | //
// AuthorizationViewController.swift
// NestLogin
//
// Created by Michael Dautermann on 11/20/15.
// Copyright © 2015 Michael Dautermann. All rights reserved.
//
import UIKit
class AuthorizationViewController: UIViewController, UIWebViewDelegate {
@IBOutlet var webView : UIWebView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let requestURL = NSURL.init(string: "https://home.nest.com/login/oauth2?client_id=27415fff-3db9-44e5-bef8-49d1f9c60bbe&state=DoingANestDemo") {
let request = NSURLRequest.init(URL: requestURL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 60.0)
webView.loadRequest(request)
}
}
func saveAccessToken(withAuthCode : String?)
{
if let authCode = withAuthCode as String! {
let url = NSURL(string: "https://api.home.nest.com/oauth2/access_token?client_id=27415fff-3db9-44e5-bef8-49d1f9c60bbe&code=\(authCode)&client_secret=DHNnft0K8OYtqfVXd3TVYU27J&grant_type=authorization_code")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let error = error {
print("error while logging in \(error.localizedDescription)")
} else {
var statusCode : Int = 200 // start off with OK
if let httpResponse = response as? NSHTTPURLResponse {
statusCode = httpResponse.statusCode
}
if(statusCode == 200) {
let stringFromData = NSString(data:data!, encoding:NSUTF8StringEncoding) as! String
do {
let parsedJson = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
guard let accessTokenDict = parsedJson as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
let expiresInSeconds = accessTokenDict["expires_in"] as! Double
let expirationDate = NSDate().dateByAddingTimeInterval(expiresInSeconds)
NSUserDefaults.standardUserDefaults().setObject(expirationDate, forKey: "expiration_date")
NSUserDefaults.standardUserDefaults().setObject(accessTokenDict["access_token"], forKey: "access_token")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loggedInVC = storyboard.instantiateViewControllerWithIdentifier("LoggedInViewController") as! LoggedInViewController
loggedInVC.accessTokenText = stringFromData
// need to do UI things on the main queue
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.navigationController?.pushViewController(loggedInVC, animated: true)
}
} catch let jsonError as NSError {
print("\(jsonError)")
}
} else {
print("Error could not login \(statusCode)")
}
}
})
task.resume()
}
}
func getAuthCode(fromURL : NSURL)
{
if let urlComponents = NSURLComponents.init(URL: fromURL, resolvingAgainstBaseURL: true)
{
if let queryItems = urlComponents.queryItems {
for item in queryItems {
if item.name == "code" {
saveAccessToken(item.value)
}
}
}
} else {
print("didn't get any url components")
}
}
// MARK: - web view delegate methods
// for some unknown reason, we're not catching the redirect happening via shouldStartLoadWithRequest
// but instead it gets caught in webViewDidFinishLoad
func webView(webView: UIWebView,
shouldStartLoadWithRequest request: NSURLRequest,
navigationType: UIWebViewNavigationType) -> Bool{
if let request = webView.request {
if let requestURL = request.URL {
if requestURL.host == "mail.deathstar.org" {
getAuthCode(requestURL)
}
}
}
return true
}
func webViewDidFinishLoad(webView: UIWebView) {
print("finished loading \(webView.request!.URL!.absoluteString)")
if let request = webView.request {
if let requestURL = request.URL {
if requestURL.host == "mail.deathstar.org" {
getAuthCode(requestURL)
}
}
}
}
func webView(webView: UIWebView,
didFailLoadWithError error: NSError?) {
print("failed loading \(webView.request!.URL!.absoluteString) with error \(error!.localizedDescription)")
}
}
| mit | c9fbd52307462c96af995e1594ac1124 | 41.471014 | 218 | 0.546664 | 5.774384 | false | false | false | false |
Rag0n/QuNotes | QuNotes/Library/LibraryTableViewCell.swift | 1 | 2271 | //
// LibraryTableViewCell.swift
// QuNotes
//
// Created by Alexander Guschin on 25.09.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
import UIKit
import FlexLayout
final class LibraryTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = AppEnvironment.current.theme.ligherDarkColor
contentView.flex.minHeight(scaledMinHeight).define {
$0.addItem(titleLabel).grow(1)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.flex.layout(mode: .adjustHeight)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
contentView.frame = CGRect(origin: contentView.frame.origin, size: size)
contentView.flex.padding(contentView.layoutMargins).layout(mode: .adjustHeight)
return contentView.frame.size
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory else { return }
contentView.flex.minHeight(scaledMinHeight)
}
func render(viewModel: Library.NotebookViewModel) {
titleLabel.markDirtyAndSetText(viewModel.title)
}
// MARK: - Private
private enum Constants {
static let minHeight: CGFloat = 44
}
private let titleLabel: UILabel = {
let l = UILabel()
let theme = AppEnvironment.current.theme
l.textColor = theme.textColor
l.backgroundColor = theme.ligherDarkColor
l.highlightedTextColor = theme.darkColor
l.numberOfLines = 0
l.font = UIFont.preferredFont(forTextStyle: .body)
l.adjustsFontForContentSizeCategory = true
l.lineBreakMode = .byWordWrapping
return l
}()
private var scaledMinHeight: CGFloat {
return UIFontMetrics(forTextStyle: .body).scaledValue(for: Constants.minHeight)
}
}
| gpl-3.0 | 973561c6c4ca144aa589ffeb9db80008 | 32.382353 | 131 | 0.698238 | 5.101124 | false | false | false | false |
naokits/my-programming-marathon | BondYTPlayerDemo/RACPlayground/ViewModel.swift | 1 | 6749 | //
// ViewModel.swift
// RACPlayground
//
// Created by Naoki Tsutsui on 8/3/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import Foundation
import Bond
import youtube_ios_player_helper
// MARK: - State Type
enum RepeatStateType {
case Off, One, All
}
enum ShuffleStateType {
case Off, On
}
enum PlayStateType {
case Pause
case Play
case TogglePlayPause
case PreviousTrack
case NextTrack
}
/*: 状態の要件
リピートボタン
状態の変更は、オフ、1曲リピート、全曲リピートという順序で変更される
状態が変更されたら、ボタンのタイトルも変更する
シャッフルボタン
状態の変更は、オフ、オンという順序で変更される
状態が変更されたら、ボタンのタイトルも変更する
*/
// MARK: - States
/// 管理する各種状態の定義
struct PlayerState {
// 再生状態(再生 or 一時停止)
var playState: PlayStateType = .Pause
// シャッフルの状態
var shuffleState = false
// リピート状態(オフ、1曲リピート、全曲リピート)
var repeaStatet: RepeatStateType = .Off
}
struct ViewModel {
// MARK: - Properties
// バックグラウンド再生の制御で使用
var isBackgroundPlay = false
var isAutoPlay = false
let playerState = Observable<YTPlayerState>(.Unstarted)
let shuffleButtonState = Observable<ShuffleStateType>(.Off)
let repeatButtonState = Observable<RepeatStateType>(.Off)
// プレイリスト
let playlist = Observable<[String]>([""])
// 再生順を格納したビデオID文字列の配列
let playIndexes = Observable<[String]>([""])
// 再生中のインデックス
let currentPlayListIndex = Observable<Int>(0)
// 自動再生
let autoPlay = Observable<Bool>(false)
let sf5Videos = ["isbHSb-dw5s", "F5lPWmPPpxI", "xNkAE09eCgw", "ON3cyF0vIjM", "hFCJ-3Y5rkM", "UeYqDQ3wxps"]
let insectVideos = ["HhkN4dZjv2c", "hJGvRkOZ2xk", "Zdd5s73HEbs"]
let miscVideos = ["vKoMlGEeZAk", "YvzB97ge80g", "aRpgTYeE0RE", "isbHSb-dw5s", "SpoAOzDmndk", "ilAB8JRMlcM", "bNJJkkW0dDU"]
let originalPlaylist = ["vKoMlGEeZAk", "YvzB97ge80g", "aRpgTYeE0RE", "isbHSb-dw5s", "SpoAOzDmndk", "ilAB8JRMlcM"]
let musicVideos = ["_Q5-4yMi-xg", "W6QjKT1A2pI", "NshFw-eUj4c", "wDIUyyQqQ_M"]
let problemVideos = ["ZwE1imnpim0", "bj5RSMOct2E"]
// MARK: - Initialize
init() {
playlist.value = musicVideos
// playlist.value = problemVideos
}
// MARK: - Functions
func updatePlayState(state: YTPlayerState) {
self.playerState.value = state
}
func isPlayingVideo() -> Bool {
return playerState.value == .Playing
}
func isEndedVideo() -> Bool {
return playerState.value == .Unstarted
}
func updateRepeatState() {
var stateValue = self.repeatButtonState.value
if stateValue == RepeatStateType.Off {
stateValue = .One
} else if stateValue == RepeatStateType.One {
stateValue = .All
} else if stateValue == RepeatStateType.All {
stateValue = RepeatStateType.Off
} else {
stateValue = RepeatStateType.Off
}
self.repeatButtonState.value = stateValue
}
func isRepeat() -> Bool {
return self.repeatButtonState.value == RepeatStateType.Off ? false : true
}
func updateShuffleState() {
var stateValue = self.shuffleButtonState.value
if stateValue == ShuffleStateType.Off {
stateValue = ShuffleStateType.On
} else if stateValue == ShuffleStateType.On {
stateValue = ShuffleStateType.Off
} else {
stateValue = ShuffleStateType.Off
}
shuffleButtonState.value = stateValue
}
func isShuffle() -> Bool {
if self.shuffleButtonState.value == .On {
return true
} else {
return false
}
}
func shufflePlaylist() {
let list = self.playlist.value
self.playlist.value.shuffle(list.count)
// シャッフルしたので、再生インデックスを先頭にする
self.currentPlayListIndex.value = 0
print("シャッフル後のリスト: \(self.playlist.value)")
}
func nextVideoIndex() {
if self.currentPlayListIndex.value < self.playlist.value.count-1 {
self.currentPlayListIndex.value += 1
} else {
// インデックスを先頭に戻す
self.currentPlayListIndex.next(0)
}
}
func previousVideoIndex() {
if self.currentPlayListIndex.value > 0 {
self.currentPlayListIndex.value -= 1
}
}
}
// MARK: - Misc View Model
class TimeViewModel : NSObject {
let timestamp = Observable<NSDate>(NSDate())
override init() {
super.init()
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(TimeViewModel.onUpdate(_:)), userInfo: nil, repeats: true)
}
func onUpdate(timer : NSTimer){
timestamp.value = NSDate()
}
}
//---------------------------------------------------------------------
/*
enum RequestState {
case None
case Requesting
case Error
}
protocol RequestListStateType {
associatedtype Item
var items: ObservableArray<Item> { get }
var requestState: Observable<RequestState> { get }
var hasVisibleItems: Observable<Bool> { get }
}
extension RequestListStateType {
func binding() {
items
.map { $0.sequence.count > 0 }
.bindTo(hasVisibleItems)
}
}
protocol RequestListType: RequestListStateType {}
extension RequestListType {
func hoge() {
self.requestState.value = .None
}
}
struct RequestListViewModel<T>: RequestListType {
typealias Item = T
let items = ObservableArray([])
let requestState = Observable<RequestState>(.None)
let hasVisibleItems = Observable<Bool>(false)
init() {
binding()
}
}
*/
// 配列をシャッフルするメソッドを追加
extension Array {
mutating func shuffle(count: Int) {
for _ in 0..<count {
self.sortInPlace({ (_, _) -> Bool in
arc4random() < arc4random()
})
}
}
}
extension NSMutableArray {
func shuffle(count: Int) {
for i in 0..<count {
let nElements: Int = count - i
let n: Int = Int(arc4random_uniform(UInt32(nElements))) + i
self.exchangeObjectAtIndex(i, withObjectAtIndex: n)
}
}
}
| mit | 1057bfce299e5240952ff360bcd50ac4 | 22.891473 | 144 | 0.608696 | 3.623751 | false | false | false | false |
RyanTech/SwinjectMVVMExample | ExampleViewModel/ImageSearchTableViewCellModel.swift | 1 | 1614 | //
// ImageSearchTableViewCellModel.swift
// SwinjectMVVMExample
//
// Created by Yoichi Tagaya on 8/22/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import ReactiveCocoa
import ExampleModel
// Inherits NSObject to use rac_willDeallocSignal.
public final class ImageSearchTableViewCellModel: NSObject, ImageSearchTableViewCellModeling {
public let id: UInt64
public let pageImageSizeText: String
public let tagText: String
private let network: Networking
private let previewURL: String
private var previewImage: UIImage?
internal init(image: ImageEntity, network: Networking) {
id = image.id
pageImageSizeText = "\(image.pageImageWidth) x \(image.pageImageHeight)"
tagText = image.tags.joinWithSeparator(", ")
self.network = network
previewURL = image.previewURL
super.init()
}
public func getPreviewImage() -> SignalProducer<UIImage?, NoError> {
if let previewImage = self.previewImage {
return SignalProducer(value: previewImage).observeOn(UIScheduler())
}
else {
let imageProducer = network.requestImage(previewURL)
.takeUntil(self.racutil_willDeallocProducer)
.on(next: { self.previewImage = $0 })
.map { $0 as UIImage? }
.flatMapError { _ in SignalProducer<UIImage?, NoError>(value: nil) }
return SignalProducer(value: nil)
.concat(imageProducer)
.observeOn(UIScheduler())
}
}
}
| mit | 1122bd040c3cb846acda95bbe94f6bd0 | 31.918367 | 94 | 0.636702 | 4.858434 | false | false | false | false |
kyouko-taiga/anzen | Tests/AnzenTests/InterpreterTests.swift | 1 | 2464 | import XCTest
import AST
import AnzenIR
import AnzenLib
import Interpreter
import SystemKit
import Utils
class InterpreterTests: XCTestCase {
override func setUp() {
guard let anzenPathname = System.environment["ANZENPATH"]
else { fatalError("missing environment variable 'ANZENPATH'") }
anzenPath = Path(pathname: anzenPathname)
guard let entryPathname = System.environment["ANZENTESTPATH"]
else { fatalError("missing environment variable 'ANZENTESTPATH'") }
entryPath = Path(pathname: entryPathname)
Path.workingDirectory = entryPath
}
var anzenPath: Path = .workingDirectory
var entryPath: Path = .workingDirectory
func testInterpreterFixtures() {
var fixtures: [String: Path] = [:]
var outputs: [String: Path] = [:]
for entry in entryPath.joined(with: "interpreter") {
if entry.fileExtension == "anzen" {
fixtures[String(entry.pathname.dropLast(6))] = entry
} else if entry.fileExtension == "output" {
outputs[String(entry.pathname.dropLast(7))] = entry
}
}
for testCase in fixtures {
let loader = DefaultModuleLoader()
let context = ASTContext(anzenPath: anzenPath, moduleLoader: loader)
guard let module = context.getModule(moduleID: .local(testCase.value)) else {
XCTFail("❌ failed to load '\(testCase.value.filename!)'")
continue
}
let driver = AIREmissionDriver()
let unit = driver.emitMainUnit(module, context: context)
guard let mainFn = unit.functions["main"] else {
XCTFail("❌ failed to load '\(testCase.value.filename!)'")
continue
}
let testResult = StringBuffer()
let interpreter = Interpreter(stdout: testResult)
do {
try interpreter.invoke(function: mainFn)
} catch {
// Explicitly silence errors.
}
if let output = outputs[testCase.key] {
let expectation = TextFile(path: output)
XCTAssertLinesEqual(try! expectation.read(), testResult.value, path: testCase.value)
print("✅ regression test succeeded for '\(testCase.value.filename!)'")
} else {
let outputPath = Path(pathname: String(testCase.value.pathname.dropLast(6)) + ".output")
let expectation = TextFile(path: outputPath)
try! expectation.write(testResult.value)
print("⚠️ no oracle for '\(testCase.value.filename!)', regression test case created now")
}
}
}
}
| apache-2.0 | 64d55b0188a8afe6804d1e024fa18a05 | 31.72 | 98 | 0.663814 | 4.216495 | false | true | false | false |
MagicLab-team/BannerView | BannerView/BannerCollectionCell.swift | 1 | 893 | //
// BannerCollectionCell.swift
// BannerView
//
// Created by Roman Sorochak on 6/29/17.
// Copyright © 2017 MagicLab. All rights reserved.
//
import UIKit
/**
BannerCollectionCell.
*/
public class BannerCollectionCell: UICollectionViewCell {
private var _imageView: UIImageView?
public var imageView: UIImageView {
get {
if let imageView = _imageView {
return imageView
}
let imageView = UIImageView(frame: bounds)
imageView.contentMode = .scaleAspectFill
contentView.addSubview(imageView)
imageView.addConstraintsAlignedToSuperview()
_imageView = imageView
return imageView
}
}
public var bannerItem: BannerItem? {
didSet {
imageView.image = bannerItem?.image
}
}
}
| mit | 0e36db65aa5e34ab6c042f91ce632377 | 21.3 | 57 | 0.584081 | 5.247059 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/Comments/Views/ViewRepliesView.swift | 1 | 1293 | import Library
import Prelude
import UIKit
final class ViewRepliesView: UIView {
// MARK: - Properties
private lazy var iconImageView: UIImageView = { UIImageView(frame: .zero) }()
private lazy var rootStackView: UIStackView = { UIStackView(frame: .zero) }()
private lazy var textLabel: UILabel = { UILabel(frame: .zero) }()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
self.configureSubviews()
self.bindStyles()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Views
private func configureSubviews() {
_ = (self.rootStackView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = ([self.textLabel, UIView(), self.iconImageView], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
}
// MARK: - Styles
override func bindStyles() {
super.bindStyles()
_ = self.rootStackView
|> viewRepliesStackViewStyle
_ = self.textLabel
|> \.text %~ { _ in Strings.View_replies() }
|> \.textColor .~ UIColor.ksr_support_400
|> \.font .~ UIFont.ksr_callout(size: 14)
_ = self.iconImageView
|> UIImageView.lens.image .~ Library.image(named: "right-diagonal")
}
}
| apache-2.0 | 6238224844008b26c6a145eca314542b | 23.865385 | 79 | 0.651199 | 4.281457 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendListCell.swift | 1 | 1588 | //
// RecommendListCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/28.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommendListCell: UITableViewCell {
var clickClosure:RecipClickClosure?
var listModel:RecipeRecommendWidgetList?{
didSet{
config((listModel?.title)!)
}
}
@IBOutlet weak var listLabel: UILabel!
func config(text:String)
{
listLabel.text = text
}
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick))
addGestureRecognizer(tap)
}
func tapClick()
{
if clickClosure != nil && listModel?.title_link != nil
{
clickClosure!((listModel?.title_link)!)
}
}
//创建cell
class func createListCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, listModel:RecipeRecommendWidgetList?) ->RecommendListCell
{
let cellID = "recommendListCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommendListCell
if cell == nil
{
cell = NSBundle.mainBundle().loadNibNamed("RecommendListCell", owner: nil, options: nil).last as? RecommendListCell
}
cell?.listModel = listModel!
return cell!
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 604285637517bb65345a7c29e286f07d | 24.852459 | 146 | 0.62714 | 4.807927 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Utility/WKInterfaceController.swift | 1 | 1258 | import WatchKit
internal extension WKInterfaceController {
private static var isSwizzled = false
private static var autoTrackerKey = UInt8()
var automaticTracker: PageTracker {
return objc_getAssociatedObject(self, &WKInterfaceController.autoTrackerKey) as? PageTracker ?? {
let tracker = DefaultPageTracker(handler: DefaultTracker.autotrackingEventHandler, viewControllerType: type(of: self))
objc_setAssociatedObject(self, &WKInterfaceController.autoTrackerKey, tracker, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return tracker
}()
}
static func setUpAutomaticTracking() {
guard !isSwizzled else {
return
}
isSwizzled = true
_ = swizzleMethod(ofType: WKInterfaceController.self, fromSelector: #selector(willActivate), toSelector: #selector(wtWillActivate))
}
@objc dynamic func wtWillActivate() {
self.wtWillActivate()
guard WebtrekkTracking.isInitialized() else {
return
}
guard let tracker = WebtrekkTracking.instance() as? DefaultTracker else {
return
}
if tracker.isApplicationActive {
automaticTracker.trackPageView()
}
}
}
| mit | 22a0e270fe34a97be2f091ecf9c7eab4 | 30.45 | 139 | 0.662957 | 5.219917 | false | false | false | false |
hugweb/StackBox | Example/StackBox/HorizontalRandomController.swift | 1 | 1947 | //
// HorizontalRandomController.swift
// PopStackView
//
// Created by Hugues Blocher on 02/06/2017.
// Copyright © 2017 Hugues Blocher. All rights reserved.
//
import UIKit
import StackBox
class HorizontalRandomController: UIViewController {
let stack = StackBoxView()
var views: [StackBoxItem] = []
override func viewDidLoad() {
super.viewDidLoad()
stack.axis = .horizontal
view.backgroundColor = UIColor.white
view.addSubview(stack)
self.navigationItem.rightBarButtonItems = [UIBarButtonItem(title: "Pop", style: .plain, target: self, action: #selector(HorizontalRandomController.pop)),
UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: self, action: nil),
UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(HorizontalRandomController.remove))]
}
func generateLabel() -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.random
label.numberOfLines = 0
label.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed efficitur augue nisi, ut placerat eros volutpat blandit. Morbi id tortor ac quam pretium egestas id eu nulla."
return label
}
func pop() {
let random = Int(arc4random_uniform(2))
let multiplier: CGFloat = [0, 20, 40, 60, 80, 100][Int(arc4random_uniform(UInt32(6)))]
let view = random == 0 ? StackBoxItem(view: generateLabel(), alignment: .trailing) : StackBoxItem(view: generateLabel(), offset: multiplier)
views.append(view)
stack.pop(views: [view])
}
func remove() {
if let view = views.last {
stack.delete(views: [view])
views.removeLast()
}
}
}
| mit | 54ebd53f9fdd64e91cbc60ddab92170c | 36.423077 | 193 | 0.62333 | 4.622328 | false | false | false | false |
pavankataria/SwiftDataTables | SwiftDataTables/Classes/SwiftDataTable.swift | 1 | 33352 | //
// SwiftDataTable.swift
// SwiftDataTables
//
// Created by Pavan Kataria on 21/02/2017.
// Copyright © 2017 Pavan Kataria. All rights reserved.
//
import UIKit
public typealias DataTableRow = [DataTableValueType]
public typealias DataTableContent = [DataTableRow]
public typealias DataTableViewModelContent = [[DataCellViewModel]]
public class SwiftDataTable: UIView {
public enum SupplementaryViewType: String {
/// Single header positioned at the top above the column section
case paginationHeader = "SwiftDataTablePaginationHeader"
/// Column header displayed at the top of each column
case columnHeader = "SwiftDataTableViewColumnHeader"
/// Footer displayed at the bottom of each column
case footerHeader = "SwiftDataTableFooterHeader"
/// Single header positioned at the bottom below the footer section.
case searchHeader = "SwiftDataTableSearchHeader"
init(kind: String){
guard let elementKind = SupplementaryViewType(rawValue: kind) else {
fatalError("Unknown supplementary view type passed in: \(kind)")
}
self = elementKind
}
}
public weak var dataSource: SwiftDataTableDataSource?
public weak var delegate: SwiftDataTableDelegate?
public var rows: DataTableViewModelContent {
return self.currentRowViewModels
}
var options: DataTableConfiguration
//MARK: - Private Properties
var currentRowViewModels: DataTableViewModelContent {
get {
return self.searchRowViewModels
}
set {
self.searchRowViewModels = newValue
}
}
fileprivate(set) open lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar()
searchBar.searchBarStyle = .minimal;
searchBar.placeholder = "Search";
searchBar.delegate = self
if #available(iOS 13.0, *) {
searchBar.backgroundColor = .systemBackground
searchBar.barTintColor = .label
} else {
searchBar.backgroundColor = .white
searchBar.barTintColor = .white
}
self.addSubview(searchBar)
return searchBar
}()
//Lazy var
fileprivate(set) open lazy var collectionView: UICollectionView = {
guard let layout = self.layout else {
fatalError("The layout needs to be set first")
}
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
if #available(iOS 13.0, *) {
collectionView.backgroundColor = UIColor.systemBackground
} else {
collectionView.backgroundColor = UIColor.clear
}
collectionView.allowsMultipleSelection = true
collectionView.dataSource = self
collectionView.delegate = self
if #available(iOS 10, *) {
collectionView.isPrefetchingEnabled = false
}
self.addSubview(collectionView)
self.registerCell(collectionView: collectionView)
return collectionView
}()
fileprivate(set) var layout: SwiftDataTableLayout? = nil {
didSet {
if let layout = layout {
self.collectionView.collectionViewLayout = layout
self.collectionView.reloadData()
}
}
}
fileprivate var dataStructure = DataStructureModel() {
didSet {
self.createDataCellViewModels(with: dataStructure)
}
}
fileprivate(set) var headerViewModels = [DataHeaderFooterViewModel]()
fileprivate(set) var footerViewModels = [DataHeaderFooterViewModel]()
fileprivate var rowViewModels = DataTableViewModelContent() {
didSet {
self.searchRowViewModels = rowViewModels
}
}
fileprivate var searchRowViewModels: DataTableViewModelContent!
fileprivate var paginationViewModel: PaginationHeaderViewModel!
fileprivate var menuLengthViewModel: MenuLengthHeaderViewModel!
fileprivate var columnWidths = [CGFloat]()
// fileprivate var refreshControl: UIRefreshControl! = {
// let refreshControl = UIRefreshControl()
// refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
// refreshControl.addTarget(self,
// action: #selector(refreshOptions(sender:)),
// for: .valueChanged)
// return refreshControl
// }()
// //MARK: - Events
// var refreshEvent: (() -> Void)? = nil {
// didSet {
// if refreshEvent != nil {
// self.collectionView.refreshControl = self.refreshControl
// }
// else {
// self.refreshControl = nil
// self.collectionView.refreshControl = nil
// }
// }
// }
// var showRefreshControl: Bool {
// didSet {
// if
// self.refreshControl
// }
// }
//MARK: - Lifecycle
public init(dataSource: SwiftDataTableDataSource,
options: DataTableConfiguration? = DataTableConfiguration(),
frame: CGRect = .zero){
self.options = options!
super.init(frame: frame)
self.dataSource = dataSource
self.set(options: options)
self.registerObservers()
}
public init(data: DataTableContent,
headerTitles: [String],
options: DataTableConfiguration = DataTableConfiguration(),
frame: CGRect = .zero)
{
self.options = options
super.init(frame: frame)
self.set(data: data, headerTitles: headerTitles, options: options, shouldReplaceLayout: true)
self.registerObservers()
}
public convenience init(data: [[String]],
headerTitles: [String],
options: DataTableConfiguration = DataTableConfiguration(),
frame: CGRect = .zero)
{
self.init(
data: data.map { $0.map { .string($0) }},
headerTitles: headerTitles,
options: options,
frame: frame
)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIApplication.willChangeStatusBarOrientationNotification, object: nil)
}
public override func layoutSubviews() {
super.layoutSubviews()
let searchBarHeight = self.heightForSearchView()
self.searchBar.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: searchBarHeight)
self.collectionView.frame = CGRect(x: 0, y: searchBarHeight, width: self.bounds.width, height: self.bounds.height-searchBarHeight)
}
func registerObservers(){
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationWillChange), name: UIApplication.willChangeStatusBarOrientationNotification, object: nil)
}
@objc func deviceOrientationWillChange() {
self.layout?.clearLayoutCache()
}
//TODO: Abstract away the registering of classes so that a user can register their own nibs or classes.
func registerCell(collectionView: UICollectionView){
let headerIdentifier = String(describing: DataHeaderFooter.self)
collectionView.register(DataHeaderFooter.self, forSupplementaryViewOfKind: SupplementaryViewType.columnHeader.rawValue, withReuseIdentifier: headerIdentifier)
collectionView.register(DataHeaderFooter.self, forSupplementaryViewOfKind: SupplementaryViewType.footerHeader.rawValue, withReuseIdentifier: headerIdentifier)
collectionView.register(PaginationHeader.self, forSupplementaryViewOfKind: SupplementaryViewType.paginationHeader.rawValue, withReuseIdentifier: String(describing: PaginationHeader.self))
collectionView.register(MenuLengthHeader.self, forSupplementaryViewOfKind: SupplementaryViewType.searchHeader.rawValue, withReuseIdentifier: String(describing: MenuLengthHeader.self))
collectionView.register(DataCell.self, forCellWithReuseIdentifier: String(describing: DataCell.self))
}
func set(data: DataTableContent, headerTitles: [String], options: DataTableConfiguration? = nil, shouldReplaceLayout: Bool = false){
self.dataStructure = DataStructureModel(data: data, headerTitles: headerTitles)
self.createDataCellViewModels(with: self.dataStructure)
self.applyOptions(options)
if(shouldReplaceLayout){
self.layout = SwiftDataTableLayout(dataTable: self)
}
}
func applyOptions(_ options: DataTableConfiguration?){
guard let options = options else {
return
}
if let defaultOrdering = options.defaultOrdering {
self.applyDefaultColumnOrder(defaultOrdering)
}
}
func calculateColumnWidths(){
//calculate the automatic widths for each column
self.columnWidths.removeAll()
for columnIndex in Array(0..<self.numberOfHeaderColumns()) {
self.columnWidths.append(self.automaticWidthForColumn(index: columnIndex))
}
self.scaleColumnWidthsIfRequired()
}
func scaleColumnWidthsIfRequired(){
guard self.shouldContentWidthScaleToFillFrame() else {
return
}
self.scaleToFillColumnWidths()
}
func scaleToFillColumnWidths(){
//if content width is smaller than ipad width
let totalColumnWidth = self.columnWidths.reduce(0, +)
let totalWidth = self.frame.width
let gap: CGFloat = totalWidth - totalColumnWidth
guard totalColumnWidth < totalWidth else {
return
}
//calculate the percentage width presence of each column in relation to the frame width of the collection view
for columnIndex in Array(0..<self.columnWidths.count) {
let columnWidth = self.columnWidths[columnIndex]
let columnWidthPercentagePresence = columnWidth / totalColumnWidth
//add result of gap size divided by percentage column width to each column automatic width.
let gapPortionToDistributeToCurrentColumn = gap * columnWidthPercentagePresence
//apply final result of each column width to the column width array.
self.columnWidths[columnIndex] = columnWidth + gapPortionToDistributeToCurrentColumn
}
}
public func reloadEverything(){
self.layout?.clearLayoutCache()
self.collectionView.reloadData()
}
public func reloadRowsOnly(){
}
public func reload(){
var data = DataTableContent()
var headerTitles = [String]()
let numberOfColumns = dataSource?.numberOfColumns(in: self) ?? 0
let numberOfRows = dataSource?.numberOfRows(in: self) ?? 0
for columnIndex in 0..<numberOfColumns {
guard let headerTitle = dataSource?.dataTable(self, headerTitleForColumnAt: columnIndex) else {
return
}
headerTitles.append(headerTitle)
}
for index in 0..<numberOfRows {
guard let rowData = self.dataSource?.dataTable(self, dataForRowAt: index) else {
return
}
data.append(rowData)
}
self.layout?.clearLayoutCache()
self.collectionView.resetScrollPositionToTop()
self.set(data: data, headerTitles: headerTitles, options: self.options)
self.collectionView.reloadData()
}
public func data(for indexPath: IndexPath) -> DataTableValueType {
return rows[indexPath.section][indexPath.row].data
}
}
public extension SwiftDataTable {
func createDataModels(with data: DataStructureModel){
self.dataStructure = data
}
func createDataCellViewModels(with dataStructure: DataStructureModel){// -> DataTableViewModelContent {
//1. Create the headers
self.headerViewModels = Array(0..<(dataStructure.headerTitles.count)).map {
let headerViewModel = DataHeaderFooterViewModel(
data: dataStructure.headerTitles[$0],
sortType: dataStructure.columnHeaderSortType(for: $0)
)
headerViewModel.configure(dataTable: self, columnIndex: $0)
return headerViewModel
}
self.footerViewModels = Array(0..<(dataStructure.footerTitles.count)).map {
let sortTypeForFooter = dataStructure.columnFooterSortType(for: $0)
let headerViewModel = DataHeaderFooterViewModel(
data: dataStructure.footerTitles[$0],
sortType: sortTypeForFooter
)
return headerViewModel
}
//2. Create the view models
//let viewModels: DataTableViewModelContent =
self.rowViewModels = dataStructure.data.map{ currentRowData in
return currentRowData.map {
return DataCellViewModel(data: $0)
}
}
self.paginationViewModel = PaginationHeaderViewModel()
self.menuLengthViewModel = MenuLengthHeaderViewModel()
// self.bindViewToModels()
}
// //MARK: - Events
// private func bindViewToModels(){
// self.menuLengthViewModel.searchTextFieldDidChangeEvent = { [weak self] text in
// self?.searchTextEntryDidChange(text)
// }
// }
//
// private func searchTextEntryDidChange(_ text: String){
// //call delegate function
// self.executeSearch(text)
// }
}
extension SwiftDataTable: UICollectionViewDataSource, UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let dataSource = self.dataSource {
return dataSource.numberOfColumns(in: self)
}
return self.dataStructure.columnCount
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
//if let dataSource = self.dataSource {
// return dataSource.numberOfRows(in: self)
//}
return self.numberOfRows()
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellViewModel: DataCellViewModel
//if let dataSource = self.dataSource {
// cellViewModel = dataSource.dataTable(self, dataForRowAt: indexPath.row)
//}
//else {
cellViewModel = self.rowModel(at: indexPath)
//}
let cell = cellViewModel.dequeueCell(collectionView: collectionView, indexPath: indexPath)
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfItemsInLine: CGFloat = 6
let inset = UIEdgeInsets.zero
// let inset = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section)
let minimumInteritemSpacing: CGFloat = 0
let contentwidth: CGFloat = minimumInteritemSpacing * (numberOfItemsInLine - 1)
let itemWidth = (collectionView.frame.width - inset.left - inset.right - contentwidth) / numberOfItemsInLine
let itemHeight: CGFloat = 100
return CGSize(width: itemWidth, height: itemHeight)
}
public func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
let kind = SupplementaryViewType(kind: elementKind)
switch kind {
case .paginationHeader:
view.backgroundColor = UIColor.darkGray
default:
if #available(iOS 13.0, *) {
view.backgroundColor = .systemBackground
} else {
view.backgroundColor = UIColor.white
}
}
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let cellViewModel = self.rowModel(at: indexPath)
if cellViewModel.highlighted {
cell.contentView.backgroundColor = delegate?.dataTable?(self, highlightedColorForRowIndex: indexPath.item) ?? self.options.highlightedAlternatingRowColors[indexPath.section % self.options.highlightedAlternatingRowColors.count]
}
else {
cell.contentView.backgroundColor = delegate?.dataTable?(self, unhighlightedColorForRowIndex: indexPath.item) ?? self.options.unhighlightedAlternatingRowColors[indexPath.section % self.options.unhighlightedAlternatingRowColors.count]
}
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let elementKind = SupplementaryViewType(kind: kind)
let viewModel: CollectionViewSupplementaryElementRepresentable
switch elementKind {
case .searchHeader: viewModel = self.menuLengthViewModel
case .columnHeader: viewModel = self.headerViewModels[indexPath.index]
case .footerHeader: viewModel = self.footerViewModels[indexPath.index]
case .paginationHeader: viewModel = self.paginationViewModel
}
return viewModel.dequeueView(collectionView: collectionView, viewForSupplementaryElementOfKind: kind, for: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.didSelectItem?(self, indexPath: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
delegate?.didDeselectItem?(self, indexPath: indexPath)
}
}
//MARK: - Swift Data Table Delegate
extension SwiftDataTable {
func disableScrollViewLeftBounce() -> Bool {
return true
}
func disableScrollViewTopBounce() -> Bool {
return false
}
func disableScrollViewRightBounce() -> Bool {
return true
}
func disableScrollViewBottomBounce() -> Bool {
return false
}
}
//MARK: - UICollection View Delegate
extension SwiftDataTable: UIScrollViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if(self.searchBar.isFirstResponder){
self.searchBar.resignFirstResponder()
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if self.disableScrollViewLeftBounce() {
if (self.collectionView.contentOffset.x <= 0) {
self.collectionView.contentOffset.x = 0
}
}
if self.disableScrollViewTopBounce() {
if (self.collectionView.contentOffset.y <= 0) {
self.collectionView.contentOffset.y = 0
}
}
if self.disableScrollViewRightBounce(){
let maxX = self.collectionView.contentSize.width-self.collectionView.frame.width
if (self.collectionView.contentOffset.x >= maxX){
self.collectionView.contentOffset.x = max(maxX-1, 0)
}
}
if self.disableScrollViewBottomBounce(){
let maxY = self.collectionView.contentSize.height-self.collectionView.frame.height
if (self.collectionView.contentOffset.y >= maxY){
self.collectionView.contentOffset.y = maxY-1
}
}
}
}
//MARK: - Refresh
extension SwiftDataTable {
// @objc fileprivate func refreshOptions(sender: UIRefreshControl) {
// self.refreshEvent?()
// }
//
// func beginRefreshing(){
// self.refreshControl.beginRefreshing()
// }
//
// func endRefresh(){
// self.refreshControl.endRefreshing()
// }
}
extension SwiftDataTable {
fileprivate func update(){
// print("\nUpdate")
self.reloadEverything()
}
fileprivate func applyDefaultColumnOrder(_ columnOrder: DataTableColumnOrder){
self.highlight(column: columnOrder.index)
self.applyColumnOrder(columnOrder)
self.sort(column: columnOrder.index, sort: self.headerViewModels[columnOrder.index].sortType)
}
func didTapColumn(index: IndexPath) {
defer {
self.update()
}
let index = index.index
self.toggleSortArrows(column: index)
self.highlight(column: index)
let sortType = self.headerViewModels[index].sortType
self.sort(column: index, sort: sortType)
}
func sort(column index: Int, sort by: DataTableSortType){
func ascendingOrder(rowOne: [DataCellViewModel], rowTwo: [DataCellViewModel]) -> Bool {
return rowOne[index].data < rowTwo[index].data
}
func descendingOrder(rowOne: [DataCellViewModel], rowTwo: [DataCellViewModel]) -> Bool {
return rowOne[index].data > rowTwo[index].data
}
switch by {
case .ascending:
self.currentRowViewModels = self.currentRowViewModels.sorted(by: ascendingOrder)
case .descending:
self.currentRowViewModels = self.currentRowViewModels.sorted(by: descendingOrder)
default:
break
}
}
func highlight(column: Int){
self.currentRowViewModels.forEach {
$0.forEach { $0.highlighted = false }
$0[column].highlighted = true
}
}
func applyColumnOrder(_ columnOrder: DataTableColumnOrder){
Array(0..<self.headerViewModels.count).forEach {
if columnOrder.index == $0 {
self.headerViewModels[$0].sortType = columnOrder.order
}
else {
self.headerViewModels[$0].sortType.toggleToDefault()
}
}
}
func toggleSortArrows(column: Int){
Array(0..<self.headerViewModels.count).forEach {
if column == $0 {
self.headerViewModels[$0].sortType.toggle()
}
else {
self.headerViewModels[$0].sortType.toggleToDefault()
}
}
// self.headerViewModels.forEach { print($0.sortType) }
}
//This is actually mapped to sections
func numberOfRows() -> Int {
return self.currentRowViewModels.count
}
func heightForRow(index: Int) -> CGFloat {
return self.delegate?.dataTable?(self, heightForRowAt: index) ?? 44
}
func rowModel(at indexPath: IndexPath) -> DataCellViewModel {
return self.currentRowViewModels[indexPath.section][indexPath.row]
}
func numberOfColumns() -> Int {
return self.dataStructure.columnCount
}
func numberOfHeaderColumns() -> Int {
return self.dataStructure.headerTitles.count
}
func numberOfFooterColumns() -> Int {
return self.dataStructure.footerTitles.count
}
func shouldContentWidthScaleToFillFrame() -> Bool{
return self.delegate?.shouldContentWidthScaleToFillFrame?(in: self) ?? self.options.shouldContentWidthScaleToFillFrame
}
func shouldSectionHeadersFloat() -> Bool {
return self.delegate?.shouldSectionHeadersFloat?(in: self) ?? self.options.shouldSectionHeadersFloat
}
func shouldSectionFootersFloat() -> Bool {
return self.delegate?.shouldSectionFootersFloat?(in: self) ?? self.options.shouldSectionFootersFloat
}
func shouldSearchHeaderFloat() -> Bool {
return self.delegate?.shouldSearchHeaderFloat?(in: self) ?? self.options.shouldSearchHeaderFloat
}
func shouldShowSearchSection() -> Bool {
return self.delegate?.shouldShowSearchSection?(in: self) ?? self.options.shouldShowSearchSection
}
func shouldShowFooterSection() -> Bool {
return self.delegate?.shouldShowSearchSection?(in: self) ?? self.options.shouldShowFooter
}
func shouldShowPaginationSection() -> Bool {
return false
}
func heightForSectionFooter() -> CGFloat {
return self.delegate?.heightForSectionFooter?(in: self) ?? self.options.heightForSectionFooter
}
func heightForSectionHeader() -> CGFloat {
return self.delegate?.heightForSectionHeader?(in: self) ?? self.options.heightForSectionHeader
}
func widthForColumn(index: Int) -> CGFloat {
//May need to call calculateColumnWidths.. I want to deprecate it..
guard let width = self.delegate?.dataTable?(self, widthForColumnAt: index) else {
return self.columnWidths[index]
}
//TODO: Implement it so that the preferred column widths are calculated first, and then the scaling happens after to fill the frame.
// if width != SwiftDataTableAutomaticColumnWidth {
// self.columnWidths[index] = width
// }
return width
}
func heightForSearchView() -> CGFloat {
guard self.shouldShowSearchSection() else {
return 0
}
return self.delegate?.heightForSearchView?(in: self) ?? self.options.heightForSearchView
}
func showVerticalScrollBars() -> Bool {
return self.delegate?.shouldShowVerticalScrollBars?(in: self) ?? self.options.shouldShowVerticalScrollBars
}
func showHorizontalScrollBars() -> Bool {
return self.delegate?.shouldShowHorizontalScrollBars?(in: self) ?? self.options.shouldShowHorizontalScrollBars
}
func heightOfInterRowSpacing() -> CGFloat {
return self.delegate?.heightOfInterRowSpacing?(in: self) ?? self.options.heightOfInterRowSpacing
}
func widthForRowHeader() -> CGFloat {
return 0
}
/// Automatically calcualtes the width the column should be based on the content
/// in the rows under the column.
///
/// - Parameter index: The column index
/// - Returns: The automatic width of the column irrespective of the Data Grid frame width
func automaticWidthForColumn(index: Int) -> CGFloat {
let columnAverage: CGFloat = CGFloat(dataStructure.averageDataLengthForColumn(index: index))
let sortingArrowVisualElementWidth: CGFloat = 10 // This is ugly
let averageDataColumnWidth: CGFloat = columnAverage + sortingArrowVisualElementWidth + (DataCell.Properties.horizontalMargin * 2)
return max(averageDataColumnWidth, max(self.minimumColumnWidth(), self.minimumHeaderColumnWidth(index: index)))
}
func calculateContentWidth() -> CGFloat {
return Array(0..<self.numberOfColumns()).reduce(self.widthForRowHeader()) { $0 + self.widthForColumn(index: $1)}
}
func minimumColumnWidth() -> CGFloat {
return 70
}
func minimumHeaderColumnWidth(index: Int) -> CGFloat {
return CGFloat(self.dataStructure.headerTitles[index].widthOfString(usingFont: UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)))
}
func heightForPaginationView() -> CGFloat {
guard self.shouldShowPaginationSection() else {
return 0
}
return 35
}
func fixedColumns() -> DataTableFixedColumnType? {
return delegate?.fixedColumns?(for: self) ?? self.options.fixedColumns
}
func shouldSupportRightToLeftInterfaceDirection() -> Bool {
return delegate?.shouldSupportRightToLeftInterfaceDirection?(in: self) ?? self.options.shouldSupportRightToLeftInterfaceDirection
}
}
//MARK: - Search Bar Delegate
extension SwiftDataTable: UISearchBarDelegate {
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.executeSearch(searchText)
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
searchBar.resignFirstResponder()
}
public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
//TODO: Use Regular expression isntead
private func filteredResults(with needle: String, on originalArray: DataTableViewModelContent) -> DataTableViewModelContent {
var filteredSet = DataTableViewModelContent()
let needle = needle.lowercased()
Array(0..<originalArray.count).forEach{
let row = originalArray[$0]
//Add some sort of index array so we use that to iterate through the columns
//The idnex array will be defined by the column definition inside the configuration object provided by the user
//Index array might look like this [1, 3, 4]. Which means only those columns should be searched into
for item in row {
let stringData: String = item.data.stringRepresentation.lowercased()
if stringData.lowercased().range(of: needle) != nil{
filteredSet.append(row)
//Stop searching through the rest of the columns in the same row and break
break;
}
}
}
return filteredSet
}
fileprivate func executeSearch(_ needle: String){
let oldFilteredRowViewModels = self.searchRowViewModels!
if needle.isEmpty {
//DONT DELETE ORIGINAL CACHE FOR LAYOUTATTRIBUTES
//MAYBE KEEP TWO COPIES.. ONE FOR SEARCH AND ONE FOR DEFAULT
self.searchRowViewModels = self.rowViewModels
}
else {
self.searchRowViewModels = self.filteredResults(with: needle, on: self.rowViewModels)
// print("needle: \(needle), rows found: \(self.searchRowViewModels!.count)")
}
self.layout?.clearLayoutCache()
// self.collectionView.scrollToItem(at: IndexPath(0), at: UICollectionViewScrollPosition.top, animated: false)
//So the header view doesn't flash when user is at the bottom of the collectionview and a search result is returned that doesn't feel the screen.
self.collectionView.resetScrollPositionToTop()
self.differenceSorter(oldRows: oldFilteredRowViewModels, filteredRows: self.searchRowViewModels)
}
private func differenceSorter(
oldRows: DataTableViewModelContent,
filteredRows: DataTableViewModelContent,
animations: Bool = false,
completion: ((Bool) -> Void)? = nil){
if animations == false {
UIView.setAnimationsEnabled(false)
}
self.collectionView.performBatchUpdates({
//finding the differences
//The currently displayed rows - in this case named old rows - is scanned over.. deleting any entries that are not existing in the newly created filtered list.
for (oldIndex, oldRowViewModel) in oldRows.enumerated() {
let index = self.searchRowViewModels.firstIndex { rowViewModel in
return oldRowViewModel == rowViewModel
}
if index == nil {
self.collectionView.deleteSections([oldIndex])
}
}
//Iterates over the new search results and compares them with the current result set displayed - in this case name old - inserting any entries that are not existant in the currently displayed result set
for (currentIndex, currentRolwViewModel) in filteredRows.enumerated() {
let oldIndex = oldRows.firstIndex { oldRowViewModel in
return currentRolwViewModel == oldRowViewModel
}
if oldIndex == nil {
self.collectionView.insertSections([currentIndex])
}
}
}, completion: { finished in
self.collectionView.reloadItems(at: self.collectionView.indexPathsForVisibleItems)
if animations == false {
UIView.setAnimationsEnabled(true)
}
completion?(finished)
})
}
}
extension SwiftDataTable {
func set(options: DataTableConfiguration? = nil){
self.layout = SwiftDataTableLayout(dataTable: self)
self.rowViewModels = DataTableViewModelContent()
self.paginationViewModel = PaginationHeaderViewModel()
self.menuLengthViewModel = MenuLengthHeaderViewModel()
//self.reload();
}
}
| mit | 6ab1d90e6e4808e1127d93421959a20f | 38.845878 | 244 | 0.645498 | 5.273719 | false | false | false | false |
xedin/swift | test/PCMacro/init.swift | 9 | 1464 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -force-single-frontend-invocation -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/PCMacroRuntime.swift %S/Inputs/SilentPlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
/*// RUN: %target-codesign %t/main*/
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
// XFAIL: *
// FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode
// UNSUPPORTED: OS=linux-gnu
import PlaygroundSupport
class A {
func access() -> Void {
}
}
class B {
var a : A = A()
init() {
a.access()
}
func mutateIvar() -> Void {
a.access()
}
}
var b = B()
// CHECK: [25:1-25:12] pc before
// this should be logging the init, this is tracked in the init.swift test.
// Once fixed update this test to include it.
// CHECK-NEXT: [17:3-17:9] pc before
// CHECK-NEXT: [17:3-17:9] pc after
// CHECK-NEXT: [18:5-18:15] pc before
// CHECK-NEXT: [11:3-11:24] pc before
// CHECK-NEXT: [11:3-11:24] pc after
// CHECK-NEXT: [18:5-18:15] pc after
// CHECK-NEXT: [25:1-25:12] pc after
| apache-2.0 | 1bec44785297dfc97ee8cbf686f372d4 | 33.046512 | 262 | 0.677596 | 2.933868 | false | true | false | false |
domenicosolazzo/practice-swift | Views/Pickers/Pickers/Pickers/CustomPickerViewController.swift | 1 | 4046 | //
// CustomPickerViewController.swift
// Pickers
//
// Created by Domenico on 20.04.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
import AudioToolbox
class CustomPickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
fileprivate var images:[UIImage]!
fileprivate var winSoundID: SystemSoundID = 0
fileprivate var crunchSoundID: SystemSoundID = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
images = [
UIImage(named: "seven")!,
UIImage(named: "bar")!,
UIImage(named: "crown")!,
UIImage(named: "cherry")!,
UIImage(named: "lemon")!,
UIImage(named: "apple")!
]
winLabel.text = " " // Note the space between the quotes
}
func showButton() {
button.isHidden = false
}
func playWinSound() {
if winSoundID == 0 {
let soundURL = Bundle.main.url(
forResource: "win", withExtension: "wav")! as CFURL
AudioServicesCreateSystemSoundID(soundURL, &winSoundID)
}
AudioServicesPlaySystemSound(winSoundID)
winLabel.text = "WINNER!"
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.showButton()
}
}
@IBOutlet weak var winLabel: UILabel!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var picker: UIPickerView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func spin(_ sender: UIButton) {
var win = false
var numInRow = -1
var lastVal = -1
for i in 0..<5 {
let newValue = Int(arc4random_uniform(UInt32(images.count)))
if newValue == lastVal {
numInRow += 1
} else {
numInRow = 1
}
lastVal = newValue
picker.selectRow(newValue, inComponent: i, animated: true)
picker.reloadComponent(i)
if numInRow >= 3 {
win = true
}
}
if crunchSoundID == 0 {
let soundURL = Bundle.main.url(
forResource: "crunch", withExtension: "wav")! as CFURL
AudioServicesCreateSystemSoundID(soundURL, &crunchSoundID)
}
AudioServicesPlaySystemSound(crunchSoundID)
if win {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.playWinSound()
}
} else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.showButton()
}
}
button.isHidden = true
winLabel.text = " " // Note the space between the quotes
}
// MARK:-
// MARK: Picker Data Source Methods
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 5
}
func pickerView(_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return images.count
}
// MARK:-
// MARK: Picker Delegate Methods
// We can supply the picker with anything that can be draw in this picker
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int,
forComponent component: Int,
reusing view: UIView?) -> UIView {
let image = images[row]
let imageView = UIImageView(image: image)
return imageView
}
func pickerView(_ pickerView: UIPickerView,
rowHeightForComponent component: Int) -> CGFloat {
return 64
}
}
| mit | d3900e335bdfcb4669ca01d564ce0e66 | 30.364341 | 140 | 0.574394 | 4.892382 | false | false | false | false |
at-internet/atinternet-ios-swift-sdk | Tracker/Tracker/Builder.swift | 1 | 24496 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// Builder.swift
// Tracker
//
import UIKit
import Foundation
/// Hit builder
class Builder: Operation {
/// Tracker instance
var tracker: Tracker
/// Contains persistent parameters
var persistentParameters: [Param]
/// Contains non persistent parameters
var volatileParameters: [Param]
// Number of configuration part
let refConfigChunks = 4
// Constant for secure configuration key
let sslKey = "secure"
// Constant for log configuration key
let logKey = "log"
// Constant for secured log configuration key
let sslLogKey = "logSSL"
// Constant for site configuration key
let siteKey = "site"
// Constant for pixel path configuration key
let pixelPathKey = "pixelPath"
// Constant for domain configuration key
let domainKey = "domain"
// Constant for Ref parameter
let referrerParameterKey = "ref"
/**
Hit builder initialization
- parameter tracker:
- parameter configuration:
- parameter volatileParameters: list of all volatile parameters
- parameter persistentParameters: list of all parameters that should be sent in all hits
- returns: A builder instance with default configuration and an empty buffer
*/
init(tracker: Tracker, volatileParameters: [Param], persistentParameters: [Param]) {
self.tracker = tracker
self.volatileParameters = volatileParameters
self.persistentParameters = persistentParameters
}
/**
Builds first half of the hit with configuration parameters
- returns: A string which represent the beginning of the hit
*/
func buildConfiguration() -> String {
var hitConf: String = ""
var hitConfChunks = 0
if (self.tracker.configuration.parameters[sslKey]?.lowercased() == "true") {
if let optLogs = self.tracker.configuration.parameters[sslLogKey] {
hitConf += "https://" + optLogs + "."
if (optLogs != "") {
hitConfChunks += 1
}
}
} else {
if let optLog = self.tracker.configuration.parameters[logKey] {
hitConf += "http://" + optLog + "."
if (optLog != "") {
hitConfChunks += 1
}
}
}
if let optDomain = self.tracker.configuration.parameters[domainKey] {
hitConf += optDomain
if (optDomain != "") {
hitConfChunks += 1
}
}
if let optPixelPath = self.tracker.configuration.parameters[pixelPathKey] {
hitConf += optPixelPath
if (optPixelPath != "") {
hitConfChunks += 1
}
}
if let optSite = self.tracker.configuration.parameters[siteKey] {
hitConf += "?s=" + optSite
if (optSite != "") {
hitConfChunks += 1
}
}
if (hitConfChunks != refConfigChunks) {
//On lève un erreur indiquant que la configuration est incorrecte
tracker.delegate?.errorDidOccur("There is something wrong with configuration: " + hitConf + ". Expected 4 configuration keys, found " + String(hitConfChunks))
hitConf = ""
}
return hitConf
}
/**
Builds the hit to be sent and slices it to chunks if too long.
- returns: A [String] representing the hit(s) to be sent
*/
func build() -> [String] {
// Hit maximum length
let hitMaxLength = 1600
// Mhid maxium length
let mhidMaxLength = 30
// Added to slices olt maximum length
let oltMaxLength = 20
// Added to slices idclient maximum length
let idclientMaxLength = 40
// Added to slices separator maximum length
let separatorMaxLength = 5
// Hits returned and ready to be sent
var hits = [String]()
// Hit chunks count
var chunksCount = 1
// Hit max chunks
let hitMaxChunks = 999
// Hit construction holder
var hit = ""
// Get the first part of the hit
let config = buildConfiguration()
// Get the parameters from the buffer (formatted as &p=v)
let formattedParams = prepareQuery()
// Reference maximum size
let refMaxSize = hitMaxLength
- mhidMaxLength
- config.characters.count
- oltMaxLength
- idclientMaxLength
- separatorMaxLength
// Hit slicing error
var err = false
let errQuery = self.makeSubQuery("mherr", value: "1")
// Idclient added to slices
let idclient = TechnicalContext.userId(tracker.configuration.parameters["identifier"])
// For each prebuilt queryString, we check the length
for queryString in formattedParams {
// If the queryString length is too long
if (queryString.str.characters.count > refMaxSize) {
// Check if the concerned parameter value in the queryString is allowed to be sliced
if (SliceReadyParam.list.contains(queryString.param.key)) {
let separator: String
if let optSeparator = queryString.param.options?.separator {
separator = optSeparator
} else {
separator = ","
}
// We slice the parameter value on the parameter separator
let components = queryString.str.components(separatedBy: "=")
let valChunks = components[1].components(separatedBy: separator)
// Parameter key to re-add on each chunks where the value is spread
var keyAdded = false
let keySplit = "&" + queryString.param.key + "="
// For each sliced value we check if we can add it to current hit, else we create and add a new hit
for valChunk in valChunks {
if (!keyAdded && (hit + keySplit + valChunk).characters.count <= refMaxSize) {
hit = hit + keySplit + valChunk
keyAdded = true
} else if (keyAdded && (hit + separator + valChunk).characters.count < refMaxSize){
hit = hit + separator + valChunk
} else {
chunksCount += 1
if (hit != "") {
hits.append(hit + separator)
}
hit = keySplit + valChunk
if (chunksCount >= hitMaxChunks) {
// Too much chunks
err = true
break
} else if (hit.characters.count > refMaxSize) {
// Value still too long
self.tracker.delegate?.warningDidOccur("Multihits: value still too long after slicing")
// Truncate the value
let idxMax = hit.index(hit.startIndex, offsetBy: refMaxSize - errQuery.characters.count)
hit = hit.substring(to: idxMax)
// Check if in the last 5 characters there is misencoded character, if so we truncate again
let idxEncode = hit.index(hit.endIndex, offsetBy: -5)
let lastChars = hit.substring(from: idxEncode)
let rangeMisencodedChar = lastChars.range(of: "%")
if rangeMisencodedChar != nil {
let idx = hit.index(hit.startIndex, offsetBy: hit.characters.count - 5)
hit = hit.substring(to: idx)
}
hit += errQuery
err = true
break
}
}
}
if (err) { break }
} else {
// Value can't be sliced
self.tracker.delegate?.warningDidOccur("Multihits: parameter value not allowed to be sliced")
hit += errQuery
break
}
// Else if the current hit + queryString length is not too long, we add it to the current hit
} else if ((hit+queryString.str).characters.count <= refMaxSize) {
hit += queryString.str
// Else, we add a new hit
} else {
chunksCount += 1
hits.append(hit)
hit = queryString.str
// Too much chunks
if (chunksCount >= hitMaxChunks) {
break
}
}
}
// We add the current working hit
hits.append(hit)
// If chunksCount > 1, we have sliced a hit
if (chunksCount > 1) {
let mhidSuffix = "-\(chunksCount)-\(self.mhidSuffixGenerator())"
for index in 0...(hits.count-1) {
if (index == (hitMaxChunks - 1)) {
// Too much chunks
self.tracker.delegate?.warningDidOccur("Multihits: too much hit parts")
hits[index] = config+errQuery
} else {
// Add the configuration, the mh variable and the idclient
let idToAdd = (index > 0) ? self.makeSubQuery("idclient", value: idclient) : ""
hits[index] = "\(config)&mh=\(index+1)\(mhidSuffix)\(idToAdd)\(hits[index])"
}
}
// Only one hit
} else {
hits[0] = config + hits[0]
}
if let delegate = tracker.delegate {
var message = ""
for hit in hits {
message += hit + "\n"
}
delegate.buildDidEnd(HitStatus.success, message: message)
}
return hits
}
/**
Sends hit
*/
override func main () {
autoreleasepool{
// Build the hit
let hits = self.build()
// Prepare a fixed olt in case of multihits and offline
var mhOlt: String?
if (hits.count > 1) {
mhOlt = String(format: "%f", Date().timeIntervalSince1970)
} else {
mhOlt = nil
}
for hit in hits {
// Wrap a hit to a sender object
let sender = Sender(tracker: self.tracker, hit: Hit(url: hit), forceSendOfflineHits:false, mhOlt: mhOlt)
sender.send()
}
}
}
/**
Sort parameters depending on their position
- parameter an: array of parameter to sort
- returns: An array of sorted parameters
*/
func organizeParameters(_ parameters: [Param]) -> [Param] {
var parameters = parameters;
let refParamPositions = Tool.findParameterPosition(referrerParameterKey, arrays: parameters)
var refParamIndex = -1
if(refParamPositions.count > 0) {
refParamIndex = refParamPositions.last!.index
}
var params = [Param]()
// Parameter with relative position set to last
var lastParameter:Param?
// Parameter with relative position set to first
var firstParameter:Param?
// ref= Parameter
var refParameter:Param?
// Handle ref= parameter which have to be in last position
if(refParamIndex > -1) {
refParameter = parameters[refParamIndex]
parameters.remove(at: refParamIndex)
if let optRefParam = refParameter {
if let optOption = optRefParam.options {
if(optOption.relativePosition != ParamOption.RelativePosition.none && optOption.relativePosition != ParamOption.RelativePosition.last) {
// Raise a warning explaining ref will always be set in last position
self.tracker.delegate?.warningDidOccur("ref= parameter will be put in last position")
}
}
}
}
for parameter in parameters {
if let optOption = parameter.options {
switch optOption.relativePosition {
// A parameter is set in first position
case ParamOption.RelativePosition.first:
if firstParameter != nil {
self.tracker.delegate?.warningDidOccur("Found more than one parameter with relative position set to first")
params.append(parameter)
} else {
params.insert(parameter, at: 0)
firstParameter = parameter
}
// A parameter is set in last position
case ParamOption.RelativePosition.last:
if lastParameter != nil{
// Raise a warning explaining there are multiple parameters with a last position indicator
self.tracker.delegate?.warningDidOccur("Found more than one parameter with relative position set to last")
params.append(parameter)
} else {
lastParameter = parameter
}
// A parameter is set before an other parameter
case ParamOption.RelativePosition.before:
if let optRelativeParamKey = optOption.relativeParameterKey {
let relativePosParam = Tool.findParameterPosition(optRelativeParamKey, arrays: parameters)
if(relativePosParam.count > 0) {
params.insert(parameter, at:relativePosParam.last!.index)
} else {
params.append(parameter)
// Raise a warning explaining that relative parameter has not been found
self.tracker.delegate?.warningDidOccur("Relative parameter with key " + optRelativeParamKey + " could not be found. Parameter will be appended")
}
}
// A parameter is set after an other parameter
case ParamOption.RelativePosition.after:
if let optRelativeParamKey = optOption.relativeParameterKey {
let relativePosParam = Tool.findParameterPosition(optRelativeParamKey, arrays: parameters)
if(relativePosParam.count > 0) {
params.insert(parameter, at:relativePosParam.last!.index + 1)
} else {
params.append(parameter)
// Raise a warning explaining that relative parameter has not been found
self.tracker.delegate?.warningDidOccur("Relative parameter with key " + optRelativeParamKey + " could not be found. Parameter will be appended")
}
}
default:
params.append(parameter)
}
} else {
params.append(parameter)
}
}
// Add the parameter marked as "last" in the collection if there is one
if let optLastParam = lastParameter {
params.append(optLastParam)
}
// Always add the parameter ref, if it exists, in last position
if let optRefParam = refParameter {
params.append(optRefParam)
}
return params;
}
/**
Prepares parameters (organize, stringify, encode) stored in the buffer to be used in the hit
- returns: An array of prepared parameters
*/
func prepareQuery() -> [(param: Param, str: String)] {
var params: [(param: Param, str: String)] = []
var bufferParams = persistentParameters + volatileParameters
bufferParams = organizeParameters(bufferParams)
for parameter in bufferParams {
var value = ""
// Plugin management
if let optPlugin = PluginParam.list(tracker)[parameter.key] {
let plugin = optPlugin.init(tracker: tracker)
plugin.execute()
parameter.key = plugin.paramKey
parameter.type = plugin.responseType
value = plugin.response
} else {
value = parameter.value()
}
if(parameter.type == .closure && value.parseJSONString != nil) {
parameter.type = .json
}
// User id hash management
if(parameter.key == HitParam.UserID.rawValue) {
if(!TechnicalContext.doNotTrack) {
if let hash = self.tracker.configuration.parameters["hashUserId"] {
if (hash.lowercased() == "true") {
value = value.sha256Value
}
}
} else {
value = "opt-out"
}
}
// Referrer processing
if(parameter.key == "ref"){
value = value.replacingOccurrences(of: "&", with: "$")
.replacingOccurrences(of: "<", with: "")
.replacingOccurrences(of: ">", with: "")
}
if let optOption = parameter.options {
if(optOption.encode) {
value = value.percentEncodedString
parameter.options!.separator = optOption.separator.percentEncodedString
}
}
// Handle parameter's value to append another
var duplicateParamIndex = -1
for(index, param) in params.enumerated() {
if(param.param.key == parameter.key)
{
duplicateParamIndex = index
break
}
}
if(duplicateParamIndex > -1) {
let duplicateParam = params[duplicateParamIndex]
// If parameter's value is JSON
if(parameter.type == .json) {
// parse string to JSON Object
let json: Any? = duplicateParam.str.components(separatedBy: "=")[1].percentDecodedString.parseJSONString
let newJson: Any? = value.percentDecodedString.parseJSONString
switch(json) {
case let dictionary as NSMutableDictionary:
switch(newJson) {
case let newDictionary as [NSObject : Any]:
dictionary.addEntries(from: newDictionary)
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let strJsonData: String = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)! as String
params[duplicateParamIndex] = (param: duplicateParam.param, str: self.makeSubQuery(parameter.key, value: strJsonData.percentEncodedString))
default:
self.tracker.delegate?.warningDidOccur("Couldn't append value to a dictionnary")
}
case let array as NSMutableArray:
switch(newJson) {
case let newArray as [Any]:
let jsonData = try? JSONSerialization.data(withJSONObject: array.addingObjects(from: newArray), options: [])
let strJsonData: String = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)! as String
params[duplicateParamIndex] = (param: duplicateParam.param, str: self.makeSubQuery(parameter.key, value: strJsonData.percentEncodedString))
default:
self.tracker.delegate?.warningDidOccur("Couldn't append value to an array")
}
default:
self.tracker.delegate?.warningDidOccur("Couldn't append a JSON")
}
} else {
if(duplicateParam.param.type == .json) {
self.tracker.delegate?.warningDidOccur("Couldn't append value to a JSON Object")
} else {
let separator: String
if(parameter.options == nil) {
separator = ","
} else {
separator = parameter.options!.separator
}
params[duplicateParamIndex] = (param: duplicateParam.param, str: duplicateParam.str + separator + value)
}
}
} else {
let prequeryInfo: (param: Param, str: String) = (param: parameter, str: self.makeSubQuery(parameter.key, value: value))
params.append(prequeryInfo)
}
}
return params
}
/**
Builds the querystring parameters
- parameter parameter: key
- parameter parameter: value
- returns: A string containing a querystring parameter
*/
func makeSubQuery(_ parameter: String, value: String) -> String {
return String(format: "&%@=%@", parameter, value)
}
/**
Builds a mhid suffix parameter
- returns: A string mhid suffix
*/
func mhidSuffixGenerator() -> String {
let randId = arc4random_uniform(10000000)
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .second], from: date)
let h = components.hour
let m = components.minute
let s = components.second
return ("\(h)\(m)\(s)\(randId)")
}
}
| mit | 232d540854faff03baebadc71db930ba | 40.026801 | 172 | 0.515004 | 5.567856 | false | true | false | false |
floriankrueger/Manuscript | Sources/Manuscript.swift | 1 | 4012 | //
// Manuscript.swift
// Manuscript
//
// Created by Florian Krüger on 17/11/14.
// Copyright (c) 2014 projectserver.org. 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
import UIKit
/// This is `Manuscript`. You should only need to interact with this part of the framework directly.
///
/// Usage:
///
/// ```
/// Manuscript.layout(<your view>) { c in
/// // create your constraints here
/// }
/// ```
///
/// See `Manuscript.layout` for more details
public struct Manuscript {
/// The identifier that is set on all created constraints if the user doesn't provide an
/// identifier. This serves at least the purpose that the user is aware which constraints are
/// created by Manuscript.
public static let defaultIdentifier = "MNSCRPT"
/// Use this to define your AutoLayout constraints in your code.
///
/// - parameter view: the `UIView` that should be layouted
/// - parameter utils: an instance of `ManuscriptUtils`, you can ignore this parameter.
/// - parameter block: a block that is provided with a `LayoutProxy` that is already setup with the
/// given `view`. You can create AutoLayout constraints through this proxy.
///
/// - returns: the `LayoutProxy` instance that is also handed to the `block`
@discardableResult public static func layout(_ view: UIView,
utils: ManuscriptUtils = Utils(),
block: (LayoutProxy) -> ()
) -> Manuscript.LayoutProxy
{
let layoutProxy = LayoutProxy(view: view, utils: utils)
block(layoutProxy)
return layoutProxy
}
static func findCommonSuperview(_ a: UIView, b: UIView?) -> UIView? {
if let b = b {
// Quick-check the most likely possibilities
if a === b { return a } // (a) and (b) are actually the same view
let (aSuper, bSuper) = (a.superview, b.superview)
if a == bSuper { return a } // (a) is the superview of (b)
if b == aSuper { return b } // (b) is the superview of (a)
if aSuper == bSuper { return aSuper }
// None of those; run the general algorithm
let ancestorsOfA = NSSet(array: Array(ancestors(a)))
for ancestor in ancestors(b) {
if ancestorsOfA.contains(ancestor) {
return ancestor
}
}
return nil // No ancestors in common
}
return a // b is nil
}
static func ancestors(_ v: UIView) -> AnySequence<UIView> {
return AnySequence { () -> AnyIterator<UIView> in
var view: UIView? = v
return AnyIterator {
let current = view
view = view?.superview
return current
}
}
}
struct Utils: ManuscriptUtils {
func isRetina() -> Bool {
return UIScreen.main.scale > 1.0
}
}
static func suffixedIdFromId(_ identifier: String?, suffix: String) -> String {
let id = identifier ?? Manuscript.defaultIdentifier
return "\(id)_\(suffix)"
}
}
| mit | ccd6ad5afdeaeaafcf55db988c0ae05d | 33.878261 | 101 | 0.66193 | 4.253446 | false | false | false | false |
davidgatti/IoT-Home-Automation | GarageOpener/GarageDoorViewController.swift | 3 | 6332 | //
// MainViewController.swift
// GarageOpener
//
// Created by David Gatti on 6/7/15.
// Copyright (c) 2015 David Gatti. All rights reserved.
//
import UIKit
import Parse
class GarageDoorViewController: UIViewController {
//MARK: Variables
var garageState = GarageState.sharedInstance
//MARK: Outlets
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var msgLastUser: UILabel!
@IBOutlet weak var msgLastUserName: UILabel!
@IBOutlet weak var msgLastDate: UILabel!
@IBOutlet weak var msgUseCount: UILabel!
@IBOutlet weak var btnOC: UIButton!
@IBOutlet weak var avatar: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Ask to be notyfied the app comes back from baground.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil)
self.loda()
}
//MARK: Functions
func loda() {
let state = self.garageDoorState()
dispatch_async(dispatch_get_main_queue()) {
// Format and display the date based on the iPhone locale.
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
//self.avatar.image = UIImage(data: (self.garageState.user.objectForKey("profilePhotho") as? PFFile)!.getData()!)
self.msgLastUserName.text = self.garageState.user.username
self.msgLastUser.text = "was the last person to " + state.str + "."
self.msgLastDate.text = formatter.stringFromDate(self.garageState.lastUsed)
self.btnOC.setTitle(state.btn, forState: UIControlState.Normal)
self.msgUseCount.text = String(self.garageState.useCount)
}
}
// Returnign the state of the garage door
func garageDoorState() -> (btn: String, str: String){
var btnState: String
var strState: String
if self.garageState.isOpen == 0 {
btnState = "Close"
strState = "open"
self.garageState.isOpen = 1
} else {
btnState = "Open"
strState = "close"
self.garageState.isOpen = 0
}
return (btnState, strState)
}
// Detect when the app coems back from the baground.
func willEnterForeground(notification: NSNotification!) {
self.performSegueWithIdentifier("backLoading", sender: self)
}
//MARK: Actions
@IBAction func openclose(sender: UIButton) {
// Disable the interface while opening/closing
sender.enabled = false
spinner.hidden = false
// First, lets check if Particle is connected.
httpGet("") { (data, error) -> Void in
if error == nil {
// If we have the remote connected to the internets,
// then we can continue getting data and show the main interface.
if data["connected"] {
// Calling the Particle function responsabile for closing and opening the garage door
httpPost("openclose", parameters: "") { (data, error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
let state = self.garageDoorState()
self.garageState.user = PFUser.currentUser()
//Updatign the interface on the main queue
dispatch_async(dispatch_get_main_queue()) {
// Update the date to now.
let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
formatter.timeStyle = .LongStyle
formatter.stringFromDate(date)
self.avatar.image = UIImage(data: (self.garageState.user.objectForKey("profilePhotho") as? PFFile)!.getData()!)
self.msgLastUserName.text = self.garageState.user.username
self.msgLastUser.text = "was the last person to " + state.str + "."
self.msgLastDate.text = formatter.stringFromDate(self.garageState.lastUsed)
sender.setTitle(state.btn, forState: UIControlState.Normal)
self.msgUseCount.text = String(self.garageState.useCount++)
// Saving settings
self.garageState.set({ (result) -> Void in })
// Reenable the user interface
sender.enabled = true
self.spinner.hidden = true
}
}
}
}
else
{
dispatch_async(dispatch_get_main_queue()) {
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("errorView") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
}
}
else
{
print(error!.localizedDescription)
}
}
}
deinit {
// make sure to remove the observer when this view controller is dismissed/deallocated
NSNotificationCenter.defaultCenter().removeObserver(self, name: nil, object: nil)
}
} | apache-2.0 | 2e213cbc6f70e9692300f9ad8e579ee2 | 39.33758 | 161 | 0.513582 | 5.653571 | false | false | false | false |
Uniprog/commom | Common/Common/Screens/Profile/ProfileVC.swift | 1 | 9004 | //
// ProfileVC.swift
// Common
//
// Created by Alexander Bukov on 4/21/15.
// Copyright (c) 2015 Uniprog. All rights reserved.
//
import UIKit
import Foundation
class ProfileVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.estimatedRowHeight = 90.0
tableView.rowHeight = UITableViewAutomaticDimension
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewTextDidChangeNotification:", name:"UITextViewTextDidChangeNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name:"UIKeyboardWillChangeFrameNotification", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// self.tableView.setNeedsLayout()
// self.tableView.layoutIfNeeded()
}
//MARK: UIViewController lifecycle
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
}
@IBAction func updateButtinClicked(sender: UIBarButtonItem) {
//tableView.reloadData()
tableView.setNeedsLayout()
tableView.layoutIfNeeded()
//tableView.visibleCells()
}
//MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProfilePhotoCell", forIndexPath: indexPath) as! UITableViewCell
configureCell(cell, forRowAtIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, forRowAtIndexPath: NSIndexPath) {
// cell.setNeedsUpdateConstraints()
// cell.updateConstraintsIfNeeded()
//
// cell.setNeedsLayout()
// cell.layoutIfNeeded()
cell.contentView.frame = cell.bounds
}
func keyboardWillChangeFrameNotification(aNotifcation: NSNotification) {
let info = aNotifcation.userInfo as NSDictionary?
let rectValue = info![UIKeyboardFrameEndUserInfoKey] as! NSValue
let kbSize = rectValue.CGRectValue().size
let contentInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0)
tableView.contentInset = contentInsets
tableView.scrollIndicatorInsets = contentInsets
// // optionally scroll
// let aRect = textView.superview!.frame
// aRect.size.height -= kbSize.height
// let targetRect = CGRectMake(0, 0, 10, 10) // get a relevant rect in the text view
// if !aRect.contains(targetRect.origin) {
// textView.scrollRectToVisible(targetRect, animated: true)
// }
}
func keyboardWillChange(notification:NSNotification) {
let userInfo = notification.userInfo!
let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
println("keyboardScreenBeginFrame \(NSStringFromCGRect(keyboardScreenBeginFrame))")
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
println("keyboardScreenEndFrame \(NSStringFromCGRect(keyboardScreenEndFrame))")
let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window)
println("keyboardViewBeginFrame \(NSStringFromCGRect(keyboardViewBeginFrame))")
let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)
println("keyboardViewEndFrame \(NSStringFromCGRect(keyboardViewEndFrame))")
let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y
println("originDelta = \(keyboardViewEndFrame.origin.y) - \(keyboardViewBeginFrame.origin.y) = \(originDelta)")
// self.replaceViewBottomConstraint.constant -= originDelta
// self.replaceViewTopConstraint.constant += originDelta
//view.setNeedsUpdateConstraints()
let oldContentInsets = tableView.contentInset;
let contentInsets = UIEdgeInsetsMake(oldContentInsets.top, oldContentInsets.left, oldContentInsets.bottom - originDelta, oldContentInsets.right)
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
//tableView.beginUpdates()
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.contentInset = contentInsets
self.tableView.scrollIndicatorInsets = contentInsets
println(NSStringFromUIEdgeInsets(contentInsets))
view.setNeedsUpdateConstraints()
view.updateConstraintsIfNeeded()
// })
//tableView.endUpdates()
// UIView.animateWithDuration(duration, delay:0, options:UIViewAnimationOptions(curve), animations: {
// self.tableView.contentInset = contentInsets
// self.tableView.scrollIndicatorInsets = contentInsets
// self.view.setNeedsLayout()
// self.view.layoutIfNeeded()
// }, completion: nil)
//
// UIView.animateWithDuration(animationDuration, delay:0, options:.BeginFromCurrentState, animations: {
// self.tableView.contentInset = contentInsets
// self.tableView.scrollIndicatorInsets = contentInsets
//
// self.view.layoutIfNeeded()
// }, completion: nil)
}
func textViewTextDidChangeNotification(notification: NSNotification){
//Action take on Notification
// - (void)scrollToCursorForTextView: (UITextView*)textView { CGRect cursorRect = [textView caretRectForPosition:textView.selectedTextRange.start]; cursorRect = [self.tableView convertRect:cursorRect fromView:textView]; if (![self rectVisible:cursorRect]) { cursorRect.size.height += 8; // To add some space underneath the cursor [self.tableView scrollRectToVisible:cursorRect animated:YES]; } }
//
return
var textView = notification.object as! UITextView
var cursorRect = textView.caretRectForPosition(textView.selectedTextRange?.start)
cursorRect = tableView.convertRect(cursorRect, fromView:textView);
//if (!self.rectvi) {
cursorRect.size.height += 8; // To add some space underneath the cursor
[tableView.scrollRectToVisible(cursorRect, animated: true)];
//}
}
// - (BOOL)rectVisible: (CGRect)rect {
// CGRect visibleRect;
// visibleRect.origin = self.tableView.contentOffset;
// visibleRect.origin.y += self.tableView.contentInset.top;
// visibleRect.size = self.tableView.bounds.size;
// visibleRect.size.height -= self.tableView.contentInset.top + self.tableView.contentInset.bottom;
//
// return CGRectContainsRect(visibleRect, rect);
// }
func keyboardDidChangeFrameNotification(aNotifcation: NSNotification) {
let info = aNotifcation.userInfo as NSDictionary?
let rectValue = info![UIKeyboardFrameEndUserInfoKey] as! NSValue
let kbSize = rectValue.CGRectValue().size
let contentInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0)
//tableView.contentInset = contentInsets
//tableView.scrollIndicatorInsets = contentInsets
// // optionally scroll
// let aRect = textView.superview!.frame
// aRect.size.height -= kbSize.height
// let targetRect = CGRectMake(0, 0, 10, 10) // get a relevant rect in the text view
// if !aRect.contains(targetRect.origin) {
// textView.scrollRectToVisible(targetRect, animated: true)
// }
}
// func scrollViewDidScroll(scrollView: UIScrollView) {
// println("entering scrollViewDidScroll function")
// }
}
| mit | 9409f982d4dc9b76d068290728e52250 | 40.114155 | 406 | 0.667592 | 5.510404 | false | false | false | false |
myriadmobile/Droar | Droar/Classes/Droar Core/DroarGestureHandler.swift | 1 | 5296 | //
// DroarGestureHandler.swift
// Droar
//
// Created by Nathan Jangula on 10/27/17.
//
import Foundation
internal extension Droar {
//State
static var openRecognizer: UIGestureRecognizer!
static var dismissalRecognizer: UISwipeGestureRecognizer!
static var threshold: CGFloat!
private static let gestureDelegate = DroarGestureDelegate()
//Setup
static func configureRecognizerForType(_ type: DroarGestureType, _ threshold: CGFloat) {
self.threshold = threshold
//Setup show gesture
switch type {
case .tripleTap:
let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTripleTap(sender:)))
recognizer.numberOfTapsRequired = 3
recognizer.delegate = gestureDelegate
replaceGestureRecognizer(with: recognizer)
case .panFromRight:
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:)))
recognizer.delegate = gestureDelegate
replaceGestureRecognizer(with: recognizer)
}
//Setup dismiss gesture
if let old = dismissalRecognizer { old.view?.removeGestureRecognizer(old) }
dismissalRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(dismissalRecognizerEvent))
dismissalRecognizer.direction = .right
dismissalRecognizer.delegate = gestureDelegate
}
//Handlers
@objc private static func handleTripleTap(sender: UITapGestureRecognizer?) {
guard let _ = sender else { print("Missing sender."); return }
toggleVisibility()
}
@objc private static func handlePan(sender: UIPanGestureRecognizer?) {
guard let sender = sender else { print("Missing sender."); return }
switch sender.state {
case .began:
// Make sure they started on the far edge
let distanceFromEdge = sender.view!.bounds.width - sender.location(in: sender.view).x
guard distanceFromEdge < threshold else { sender.isEnabled = false; break }
guard beginDroarVisibilityUpdate() else { sender.isEnabled = false; break }
case .changed:
let limitedPan = max(sender.translation(in: sender.view).x, -navController.view.frame.width)
navController.view.transform = CGAffineTransform(translationX: limitedPan, y: 0)
let percent = abs(limitedPan) / drawerWidth
window.setActivationPercent(percent)
default:
sender.isEnabled = true
//Gesture finished; now we must determine what the final state is.
if abs(navController.view.transform.tx) >= (navController.view.frame.size.width / 2) {
openDroar()
} else {
closeDroar()
}
}
}
//Visibility Updates
private static func beginDroarVisibilityUpdate() -> Bool {
//Ensure the window is visible
let appWindow = loadKeyWindow()
window.makeKeyAndVisible()
window.addSubview(navController.view)
appWindow?.makeKeyAndVisible()
//Update for knob state
KnobManager.sharedInstance.registerDynamicKnobs(loadDynamicKnobs())
KnobManager.sharedInstance.prepareForDisplay(tableView: viewController?.tableView)
return true
}
private static func loadDynamicKnobs() -> [DroarKnob] {
//Note: I think this dynamic knob feature could use some rethinking.
if let activeVC = loadActiveResponder() {
let candidateVCs = activeVC.loadActiveViewControllers()
var knobs = [DroarKnob]()
for candidate in candidateVCs {
if candidate is DroarKnob {
knobs.append(candidate as! DroarKnob)
}
}
return knobs
}
return []
}
//Convenience
static func replaceGestureRecognizer(with recognizer: UIGestureRecognizer) {
//Remove old (if applicable)
if let gestureRecognizer = openRecognizer {
gestureRecognizer.view?.removeGestureRecognizer(gestureRecognizer)
}
//Add new
openRecognizer = recognizer
loadKeyWindow()?.addGestureRecognizer(openRecognizer)
}
@objc private static func dismissalRecognizerEvent() { closeDroar() } //We can't call closeDroar from the selector because of the optional completion block
}
//Gesture Delegates
fileprivate class DroarGestureDelegate: NSObject, UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == Droar.openRecognizer {
} else if gestureRecognizer == Droar.dismissalRecognizer {
if touch.view is UISlider { return false } //Prevent pan from interfering with slider
}
return true
}
}
| mit | f14a709c96786b3d95b795cb4e56f8fe | 36.295775 | 164 | 0.641616 | 5.431795 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift | TLTranstionLib-swift/Classes/Interactors/TLHorizontalInteraction.swift | 1 | 1772 | //
// TLHorizontalInteraction.swift
// Pods
//
// Created by Andrew on 16/8/8.
//
//
import UIKit
private let HorizontalTransitionCompletionPercentage:CGFloat = 0.3
public class TLHorizontalInteraction: TLBaseSwipeInteraction {
override func isGesturePositive(panGestureRecognizer: UIPanGestureRecognizer) -> Bool {
return self.translationWithPanGestureRecongizer(panGestureRecognizer: panGestureRecognizer) < 0
}
override func swipeCompletionPercent() -> CGFloat {
return HorizontalTransitionCompletionPercentage
}
override func translationPercentageWithPanGestureRecongizer(panGestureRecognizer panGestureRecognizer: UIPanGestureRecognizer) -> CGFloat {
return fabs(self.translationWithPanGestureRecongizer(panGestureRecognizer: panGestureRecognizer)/(panGestureRecognizer.view?.bounds.size.width)!)
}
/**
手指实际滑动的距离
- parameter panGestureRecognizer: 手势
- returns: 返回手指移动的距离
*/
override func translationWithPanGestureRecongizer(panGestureRecognizer panGestureRecognizer: UIPanGestureRecognizer) -> CGFloat {
return panGestureRecognizer.translationInView(panGestureRecognizer.view).x
}
//MARK: - UIGestureRecognizerDelegate
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UIPanGestureRecognizer{
let panGesture = gestureRecognizer as! UIPanGestureRecognizer
//在Y轴移动的距离
let yTranslation = panGesture.translationInView(panGesture.view).y
return yTranslation == 0
}
return true
}
}
| mit | 09634945d6b5df1a20a9d0f95232b1be | 28.118644 | 153 | 0.707218 | 6.006993 | false | false | false | false |
heartfly/DropdownMenu | Source/DropdownMenu.swift | 2 | 14211 | //
// DropdownMenu.swift
// DropdownMenu
//
// Created by qxh on 16/1/22.
// Copyright © 2016 qxh. All rights reserved.
//
import UIKit
// MARK: - DropdownMenu Mixin
@objc public protocol DropdownMenuMixin {
//navigationBar title menu
optional var titleDropdownMenu: DropdownMenu { get set }
optional func setupTitleDropdownMenu(items: [String])
//navigationBar title multisection menu
optional var multiSectionTitleDropdownMenu: DropdownMenu { get set }
optional func setupMultiSectionTitleDropdownMenu(items: [String])
//navigationBar right menu
optional var rightDropdownMenu: DropdownMenu { get set }
optional func setupRightDropdownMenu(items: [String])
}
// Providing Default Implementations of DropdownMenuMixin
extension DropdownMenuMixin where Self: UIViewController {
public var titleDropdownMenu: DropdownMenu {
get {
var bounds = self.view.bounds
bounds.origin.y = (self.navigationController?.navigationBar.bounds.height)! + UIApplication.sharedApplication().statusBarFrame.size.height
let menu = DropdownMenu(frame: bounds, type: .Grid, position: .Middle, items: []) { (indexPath, item) -> Void in
if let titleView = self.navigationItem.titleView as? TappableTitleView {
titleView.title = item
}
}
self.navigationItem.titleView = TappableTitleView(title: self.title, tapHandler: { [unowned menu] () -> Void in
menu.toggle()
})
self.view.addSubview(menu)
return menu
}
}
public func setupTitleDropdownMenu(items: [String]) {
self.titleDropdownMenu.items = items
}
public var rightDropdownMenu: DropdownMenu {
get {
var bounds = self.view.bounds
bounds.origin.y = (self.navigationController?.navigationBar.bounds.height)! + UIApplication.sharedApplication().statusBarFrame.size.height
let menu = DropdownMenu(frame: bounds, type: .Table, position: .Right, items: []) { (indexPath) -> Void in
}
self.navigationItem.titleView = TappableTitleView(title: self.title, tapHandler: { [unowned menu] () -> Void in
menu.toggle()
})
self.view.addSubview(menu)
return menu
}
}
public func setupRightDropdownMenu(items: [String]) {
self.rightDropdownMenu.items = items
}
public var multiSectionTitleDropdownMenu: DropdownMenu {
get {
var bounds = self.view.bounds
bounds.origin.y = (self.navigationController?.navigationBar.bounds.height)! + UIApplication.sharedApplication().statusBarFrame.size.height
let menu = DropdownMenu(frame: bounds, type: .Grid, position: .Middle, sections: []) { (indexPath) -> Void in
}
self.navigationItem.titleView = TappableTitleView(title: self.title, tapHandler: { [unowned menu] () -> Void in
menu.toggle()
})
self.view.addSubview(menu)
return menu
}
}
public func setupMultiSectionTitleDropdownMenu(sections: [(title: String, items: [String])]) {
self.multiSectionTitleDropdownMenu.sections = sections
}
}
// MARK: - Dropdownable protocol
public protocol Dropdownable {
var isShown: Bool { get set }
func show()
func hide()
func toggle()
func showMenu()
func hideMenu()
}
// Providing Default Implementations of Dropdownable
extension Dropdownable where Self: UIView {
public func show() {
if self.isShown == false {
self.showMenu()
}
}
public func hide() {
if self.isShown == true {
self.hideMenu()
}
}
public func toggle() {
if self.isShown == true {
self.hideMenu()
} else {
self.showMenu()
}
}
}
// Drop down view type
public enum DropdownMenuType {
case Grid // show as Grid
case Table // show as Table
}
// Drop down position
public enum DropdownMenuPostion {
case Middle // at middle
case Right // at right
}
// MARK: - DropdownMenu Control
let DropdownCollectionViewCellIdentifier:String = "DropdownCollectionViewCell"
public class DropdownMenu: UIView, Dropdownable, UICollectionViewDataSource, UICollectionViewDelegate {
public var type: DropdownMenuType = .Table
public var position: DropdownMenuPostion = .Middle
public var width: CGFloat = UIScreen.mainScreen().bounds.width // menu width
public var items: [String] = [] {
didSet {
self.reloadData()
}
}// menu item titles (for Table type)
public var sections: [(title: String, items: [String])] = [] // menu sections ( for CollectionType)
public var isShown: Bool = false
public var tableView: UITableView?
public let margin: CGFloat = 5.0
public let cellHeight: CGFloat = 40.0
public var didSelectItemHandler: (indexPath: NSIndexPath, item: String) -> Void = { _ in }
lazy var backgroundView: UIView = {
let _backgroundView = UIView(frame: self.bounds)
_backgroundView.backgroundColor = UIColor.blackColor()
_backgroundView.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
let backgroundTapRecognizer = UITapGestureRecognizer(target: self, action: "hideMenu");
_backgroundView.addGestureRecognizer(backgroundTapRecognizer)
return _backgroundView
}()
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let _collectionView = UICollectionView(frame: CGRectMake(0, 0, CGFloat(self.width), CGFloat(320)), collectionViewLayout: layout)
_collectionView.delegate = self
_collectionView.dataSource = self
// register CollectionViewCell
_collectionView.registerClass(UICollectionViewCell.self,
forCellWithReuseIdentifier: DropdownCollectionViewCellIdentifier)
_collectionView.backgroundColor = UIColor(red:0.298, green:0.643, blue:0.984, alpha: 1)
_collectionView.opaque = false
_collectionView.showsHorizontalScrollIndicator = false
_collectionView.showsVerticalScrollIndicator = false
_collectionView.clipsToBounds = false
return _collectionView
}()
public init(frame: CGRect, type: DropdownMenuType, position: DropdownMenuPostion, items: [String], sections: [(title: String, items: [String])], didSelectItemHandler: (indexPath: NSIndexPath, item: String) -> Void) {
// Set frame
super.init(frame: frame)
self.type = type
self.position = position
self.items = items
self.sections = sections
self.didSelectItemHandler = didSelectItemHandler
self.clipsToBounds = true
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
self.addSubview(backgroundView)
self.addSubview(collectionView)
self.hidden = true
}
public convenience init(frame: CGRect, type: DropdownMenuType, position: DropdownMenuPostion, items: [String], didSelectItemHandler: (indexPath: NSIndexPath, item: String) -> Void) {
self.init(frame: frame, type: type, position: position, items: items, sections: [], didSelectItemHandler: didSelectItemHandler)
}
public convenience init(frame: CGRect, type: DropdownMenuType, position: DropdownMenuPostion, sections: [(title: String, items: [String])], didSelectItemHandler: (indexPath: NSIndexPath, item: String) -> Void) {
self.init(frame: frame, type: type, position: position, items: [], sections: sections, didSelectItemHandler: didSelectItemHandler)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func reloadData() {
let layout = UICollectionViewFlowLayout()
let totalWidth = self.width - self.margin*2
var cellWidth: CGFloat = 0.0
var collectionHeight: CGFloat = 0.0
switch self.type {
case .Grid:
if self.items.count > 0 {
if self.items.count >= 3 {
cellWidth = totalWidth/3 - self.margin*2
collectionHeight = CGFloat(self.items.count/3+1) * self.cellHeight
} else {
cellWidth = totalWidth/2 - self.margin*2
collectionHeight = self.cellHeight
}
} else if self.sections.count > 0 {
if self.sections[0].1.count >= 3 {
cellWidth = totalWidth/3 - self.margin*2
} else {
cellWidth = totalWidth/2 - self.margin*2
}
for (_, items) in self.sections {
if items.count >= 3 {
collectionHeight += CGFloat(self.items.count/3+1) * self.cellHeight
} else {
collectionHeight += self.cellHeight
}
collectionHeight += 30
}
}
case .Table:
cellWidth = self.width
collectionHeight = CGFloat(self.items.count) * self.cellHeight
}
layout.itemSize = CGSizeMake(CGFloat(cellWidth), self.cellHeight - 10)
layout.scrollDirection = UICollectionViewScrollDirection.Vertical //scroll direction
layout.minimumLineSpacing = 5.0 // line spacing
layout.minimumInteritemSpacing = 5.0 // item spacing
layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) // section spacing
layout.headerReferenceSize = CGSize(width: CGFloat(self.width), height: CGFloat(320))
self.collectionView.frame = CGRectMake(0, 0, CGFloat(self.width), CGFloat(320) + collectionHeight)
self.collectionView.collectionViewLayout = layout
}
// MARK: - Dropdownable
public func showMenu() {
self.isShown = true
// Visible menu view
self.hidden = false
// Change background alpha
self.backgroundView.alpha = 0
// Animation
self.collectionView.frame.origin.y = -self.collectionView.frame.size.height
self.superview?.bringSubviewToFront(self)
UIView.animateWithDuration(
0.3,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
self.collectionView.frame.origin.y = CGFloat(-320)
self.backgroundView.alpha = 0.3
}, completion: nil
)
}
public func hideMenu() {
self.isShown = false
// Change background alpha
self.backgroundView.alpha = 0.3
UIView.animateWithDuration(
0.2,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.5,
options: [],
animations: {
[unowned self] _ in
self.collectionView.frame.origin.y = CGFloat(-280)
}, completion: nil
)
// Animation
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { [unowned self] _ in
self.collectionView.frame.origin.y = -self.collectionView.frame.size.height
self.backgroundView.alpha = 0
}, completion: { [unowned self] _ in
self.hidden = true
})
}
// MARK: - UICollectionViewDataSource
// CollectionView sections number
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
if self.sections.count > 0 {
return self.sections.count
}
return 1
}
// CollectionView items number
public func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
if self.sections.count > 0 {
let (_, items) = self.sections[section]
return items.count
}
return self.items.count
}
// setup cepublic ll
public func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
DropdownCollectionViewCellIdentifier, forIndexPath: indexPath) as UICollectionViewCell
// show menu title
var item: String
if self.sections.count > 0 {
let (_, items) = self.sections[indexPath.section]
item = items[indexPath.row]
} else {
item = self.items[indexPath.row]
}
if let textLabel: UILabel = cell.viewWithTag(10086) as? UILabel {
textLabel.text = item
} else {
let lbl = UILabel(frame:CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height))
lbl.backgroundColor = UIColor.whiteColor()
lbl.layer.borderWidth = 1
lbl.layer.borderColor = UIColor.grayColor().CGColor
lbl.textAlignment = NSTextAlignment.Center
cell.addSubview(lbl)
lbl.tag = 10086
lbl.text = item
}
return cell
}
// MARK: - UICollectionViewDelegate
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var item: String = ""
if self.sections.count > 0 {
item = self.sections[indexPath.section].items[indexPath.row]
} else {
item = self.items[indexPath.row]
}
self.hide()
self.didSelectItemHandler(indexPath: indexPath, item: item)
}
}
| mit | 8ff8fd5c89f0b0d016457d60a81768d4 | 36.592593 | 220 | 0.613089 | 5.176685 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeDownloading/AwesomeDownloading/Classes/AwesomeDownloading.swift | 1 | 5019 | //
// AwesomeDownloading.swift
// AwesomeDownloading
//
// Created by Emmanuel on 10/06/2018.
//
import Foundation
import UIKit
public typealias ProgressCallback = (Float) -> ()
public typealias DownloadedCallback = (Bool) -> ()
public enum AwesomeMediaDownloadState {
case downloading
case downloaded
case none
}
public class AwesomeDownloading: NSObject {
// public shared
public static var shared = AwesomeDownloading()
// Private variables
fileprivate var session: URLSession?
fileprivate var downloadTask: URLSessionDownloadTask?
fileprivate var downloadUrl: URL?
// Callbacks
public var progressCallback: ProgressCallback?
public var downloadedCallback: DownloadedCallback?
public static func mediaDownloadState(withUrl url: URL?) -> AwesomeMediaDownloadState {
guard let downloadUrl = url else {
return .none
}
if downloadUrl.offlineFileExists {
print("File \(downloadUrl) is offline")
return .downloaded
}
return .none
}
public static func downloadMedia(withUrl url: URL?, completion: @escaping DownloadedCallback, progressUpdated: @escaping ProgressCallback){
guard let downloadUrl = url else {
completion(false)
return
}
// to check if it exists before downloading it
if downloadUrl.offlineFileExists {
print("The file already exists at path")
completion(true)
} else {
shared.progressCallback = progressUpdated
shared.downloadedCallback = completion
shared.startDownloadSession(withUrl: downloadUrl)
}
}
public static func deleteDownloadedMedia(withUrl url: URL?, completion:@escaping (Bool) -> Void){
guard let downloadUrl = url else {
completion(false)
return
}
downloadUrl.deleteOfflineFile(completion)
}
}
extension AwesomeDownloading {
fileprivate func startDownloadSession(withUrl url: URL) {
downloadUrl = url
let configuration = URLSessionConfiguration.default
//let queue = NSOperationQueue.mainQueue()
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
downloadTask = session?.downloadTask(with: url)
downloadTask?.resume()
}
fileprivate func finishDownloadSession() {
session?.finishTasksAndInvalidate()
session = nil
downloadTask?.cancel()
downloadTask = nil
}
}
extension AwesomeDownloading: URLSessionDelegate, URLSessionDownloadDelegate {
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
finishDownloadSession()
guard let downloadUrl = downloadUrl else {
return
}
location.moveOfflineFile(to: downloadUrl.offlineFileDestination, completion: { (success) in
DispatchQueue.main.async {
self.downloadedCallback?(success)
}
})
}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
DispatchQueue.main.async {
self.progressCallback?(progress)
}
}
}
extension UIViewController {
public func confirmMediaDeletion(withUrl url: URL?, fromView: UIView? = nil, withTitle title: String, withMessage message: String, withConfirmButtonTitle confirmButtonTitle:String, withCancelButtonTitle cancelButtonTitle:String, completion:@escaping (Bool) -> Void) {
guard let downloadUrl = url else {
completion(false)
return
}
// we should delete the media.
let alertController = UIAlertController(
title: title,
message: message,
preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(
title: confirmButtonTitle,
style: .destructive,
handler: { (action) in
downloadUrl.deleteOfflineFile { (success) in
DispatchQueue.main.async {
completion(success)
}
}
}))
alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: { (action) in
}))
if let fromView = fromView {
alertController.popoverPresentationController?.sourceView = fromView
alertController.popoverPresentationController?.sourceRect = fromView.bounds
}
present(alertController, animated: true, completion: nil)
}
}
| mit | 93b9495d84a763b575766115202b49e7 | 30.566038 | 271 | 0.632795 | 5.749141 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Tools/STPageView/STPageView.swift | 1 | 1914 | //
// STPageView.swift
// STPageView
//
// Created by xiudou on 2016/12/5.
// Copyright © 2016年 CoderST. All rights reserved.
// 主要的View
import UIKit
class STPageView: UIView {
// MARK:- 定义属性
fileprivate var titles : [String]
fileprivate var childsVC : [UIViewController]
fileprivate var parentVC : UIViewController
fileprivate var style : STPageViewStyle
fileprivate var titleView : STTitlesView!
// MARK:- 自定义构造函数
init(frame: CGRect, titles : [String], childsVC : [UIViewController], parentVC : UIViewController, style : STPageViewStyle) {
// 初始化前一定要给属性赋值,不然会报super dont init 错误
self.titles = titles
self.parentVC = parentVC
self.childsVC = childsVC
self.style = style
super.init(frame: frame)
stupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension STPageView {
fileprivate func stupUI(){
stupTitleView()
setupContentView()
}
fileprivate func stupTitleView(){
let titleviewF = CGRect(x: 0, y: 0, width: self.frame.width, height: style.titleViewHeight)
titleView = STTitlesView(frame: titleviewF, titles: self.titles, style: self.style)
titleView.backgroundColor = style.titleViewBackgroundColor
addSubview(titleView)
}
fileprivate func setupContentView(){
let contentViewF = CGRect(x: 0, y: style.titleViewHeight, width: self.frame.width, height: self.frame.height - style.titleViewHeight)
let contentView = STContentView(frame: contentViewF, childsVC: self.childsVC, parentVC: self.parentVC)
addSubview(contentView)
titleView.delegate = contentView
contentView.delegate = titleView
}
}
| mit | 23d1fd0ac8dd0eff73b4d27f6c0c5d1a | 27.859375 | 141 | 0.654034 | 4.571782 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/KeyVerification/Common/Loading/KeyVerificationDataLoadingViewModel.swift | 1 | 5664 | // File created from ScreenTemplate
// $ createScreen.sh DeviceVerification/Loading DeviceVerificationDataLoading
/*
Copyright 2019 New Vector Ltd
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
enum KeyVerificationDataLoadingViewModelError: Error {
case unknown
case transactionCancelled
case transactionCancelledByMe(reason: MXTransactionCancelCode)
}
final class KeyVerificationDataLoadingViewModel: KeyVerificationDataLoadingViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private(set) var verificationKind: KeyVerificationKind
private let otherUserId: String?
private let otherDeviceId: String?
private let keyVerificationService = KeyVerificationService()
private let keyVerificationRequest: MXKeyVerificationRequest?
private var currentOperation: MXHTTPOperation?
// MARK: Public
weak var viewDelegate: KeyVerificationDataLoadingViewModelViewDelegate?
weak var coordinatorDelegate: KeyVerificationDataLoadingViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, verificationKind: KeyVerificationKind, otherUserId: String, otherDeviceId: String) {
self.session = session
self.verificationKind = verificationKind
self.otherUserId = otherUserId
self.otherDeviceId = otherDeviceId
self.keyVerificationRequest = nil
}
init(session: MXSession, verificationKind: KeyVerificationKind, keyVerificationRequest: MXKeyVerificationRequest) {
self.session = session
self.verificationKind = verificationKind
self.otherUserId = nil
self.otherDeviceId = nil
self.keyVerificationRequest = keyVerificationRequest
}
deinit {
self.currentOperation?.cancel()
}
// MARK: - Public
func process(viewAction: KeyVerificationDataLoadingViewAction) {
switch viewAction {
case .loadData:
self.loadData()
case .cancel:
self.coordinatorDelegate?.keyVerificationDataLoadingViewModelDidCancel(self)
}
}
// MARK: - Private
private func loadData() {
if let keyVerificationRequest = self.keyVerificationRequest {
self.acceptKeyVerificationRequest(keyVerificationRequest)
} else {
self.downloadOtherDeviceKeys()
}
}
private func acceptKeyVerificationRequest(_ keyVerificationRequest: MXKeyVerificationRequest) {
self.update(viewState: .loading)
keyVerificationRequest.accept(withMethods: self.keyVerificationService.supportedKeyVerificationMethods(), success: { [weak self] in
guard let self = self else {
return
}
self.coordinatorDelegate?.keyVerificationDataLoadingViewModel(self, didAcceptKeyVerificationRequest: keyVerificationRequest)
}, failure: { [weak self] (error) in
guard let self = self else {
return
}
self.update(viewState: .error(error))
})
}
private func downloadOtherDeviceKeys() {
guard let crypto = session.crypto,
let otherUserId = self.otherUserId,
let otherDeviceId = self.otherDeviceId else {
self.update(viewState: .errorMessage(VectorL10n.deviceVerificationErrorCannotLoadDevice))
NSLog("[KeyVerificationDataLoadingViewModel] Error session.crypto is nil")
return
}
if let otherUser = session.user(withUserId: otherUserId) {
self.update(viewState: .loading)
self.currentOperation = crypto.downloadKeys([otherUserId], forceDownload: false, success: { [weak self] (usersDevicesMap, crossSigningKeysMap) in
guard let sself = self else {
return
}
if let otherDevice = usersDevicesMap?.object(forDevice: otherDeviceId, forUser: otherUserId) {
sself.update(viewState: .loaded)
sself.coordinatorDelegate?.keyVerificationDataLoadingViewModel(sself, didLoadUser: otherUser, device: otherDevice)
} else {
sself.update(viewState: .errorMessage(VectorL10n.deviceVerificationErrorCannotLoadDevice))
}
}, failure: { [weak self] (error) in
guard let sself = self else {
return
}
let finalError = error ?? KeyVerificationDataLoadingViewModelError.unknown
sself.update(viewState: .error(finalError))
})
} else {
self.update(viewState: .errorMessage(VectorL10n.deviceVerificationErrorCannotLoadDevice))
}
}
private func update(viewState: KeyVerificationDataLoadingViewState) {
self.viewDelegate?.keyVerificationDataLoadingViewModel(self, didUpdateViewState: viewState)
}
}
| apache-2.0 | 16d4e0c72dc4e95f96a79efe0acae35b | 36.019608 | 157 | 0.654838 | 5.893861 | false | false | false | false |
ilg/ElJayKit.swift | Pod/API/PublicRemoteMethods/friends.swift | 1 | 1669 | //
// friends.swift
// ElJayKit
//
// Created by Isaac Greenspan on 12/13/15.
// Copyright © 2015 Isaac Greenspan. All rights reserved.
//
import Foundation
import AlamofireXMLRPC
extension API {
public func friendOf(callback callback: Of<[Friend]>.callback) {
self.execute(.friendOf, callback: callback)
}
public func getFriendGroups(callback callback: Of<[FriendGroup]>.callback) {
self.execute(.getFriendGroups, callback: callback)
}
public struct GetFriendsResult {
let friends: [Friend]
let friendOf: [Friend]?
let friendGroups: [FriendGroup]?
}
public func getFriends(
includeFriendOf includeFriendOf: Bool = false,
includeGroups: Bool = false,
includeBirthdays: Bool = false,
callback: Of<GetFriendsResult>.callback) {
self.execute(
.getFriends,
parameters: [
ParameterKey.IncludeFriendOf: ParameterValue.fromBool(includeFriendOf),
ParameterKey.IncludeGroups: ParameterValue.fromBool(includeGroups),
ParameterKey.IncludeBirthdays: ParameterValue.fromBool(includeBirthdays),
],
callback: callback)
}
}
extension API.GetFriendsResult: XMLRPCDeserializable {
init(xmlrpcNode value: XMLRPCNode) throws {
self.friends = try ¿value[API.ResponseKey.Friends].arrayOfType(API.Friend.self)
self.friendOf = try? ¿value[API.ResponseKey.FriendOfs].arrayOfType(API.Friend.self)
self.friendGroups = try? ¿value[API.ResponseKey.FriendGroups].arrayOfType(API.FriendGroup.self)
}
}
| mit | 5317dcd20cdf150eac11a069b232ae1e | 32.979592 | 103 | 0.654655 | 4.247449 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Stream/PostbarController.swift | 1 | 20767 | ////
/// PostbarController.swift
//
@objc
protocol LoveableCell: class {
func toggleLoveControl(enabled: Bool)
func toggleLoveState(loved: Bool)
}
class PostbarController: UIResponder {
override var canBecomeFirstResponder: Bool {
return true
}
override var next: UIResponder? {
return responderChainable?.next()
}
var responderChainable: ResponderChainableController?
weak var streamViewController: StreamViewController!
weak var collectionViewDataSource: CollectionViewDataSource!
// overrideable to make specs easier to write
weak var collectionView: UICollectionView!
var currentUser: User? { return streamViewController.currentUser }
// on the post detail screen, the comments don't show/hide
var toggleableComments: Bool = true
init(
streamViewController: StreamViewController,
collectionViewDataSource: CollectionViewDataSource
) {
self.streamViewController = streamViewController
self.collectionView = streamViewController.collectionView
self.collectionViewDataSource = collectionViewDataSource
}
// in order to include the `StreamViewController` in our responder chain
// search, we need to ask it directly for the correct responder. If the
// `StreamViewController` isn't returned, this function returns the same
// object as `findResponder`
func findProperResponder<T>() -> T? {
if let responder:T? = findResponder() {
return responder
}
else {
return responderChainable?.controller?.findResponder()
}
}
func viewsButtonTapped(cell: UICollectionViewCell) {
guard
let indexPath = collectionView.indexPath(for: cell),
let post = collectionViewDataSource.post(at: indexPath)
else { return }
Tracker.shared.viewsButtonTapped(post: post)
let responder: StreamPostTappedResponder? = findProperResponder()
responder?.postTappedInStream(cell)
}
func viewsButtonTapped(post: Post, scrollToComments: Bool) {
Tracker.shared.viewsButtonTapped(post: post)
let responder: PostTappedResponder? = findProperResponder()
responder?.postTapped(post, scrollToComments: scrollToComments)
}
func commentsButtonTapped(cell: StreamFooterCell, imageLabelControl: ImageLabelControl) {
guard
let indexPath = collectionView.indexPath(for: cell),
let item = collectionViewDataSource.streamCellItem(at: indexPath)
else { return }
guard collectionViewDataSource.isFullWidth(at: indexPath) else {
cell.cancelCommentLoading()
viewsButtonTapped(cell: cell)
return
}
guard toggleableComments else {
cell.cancelCommentLoading()
return
}
guard
let post = item.jsonable as? Post
else {
cell.cancelCommentLoading()
return
}
if let commentCount = post.commentsCount, commentCount == 0, currentUser == nil {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard !streamViewController.streamKind.isDetail(post: post) else {
return
}
imageLabelControl.isSelected = cell.commentsOpened
cell.comments.isEnabled = false
if !cell.commentsOpened {
streamViewController.removeComments(forPost: post)
item.state = .collapsed
imageLabelControl.isEnabled = true
imageLabelControl.finishAnimation()
imageLabelControl.isHighlighted = false
}
else {
item.state = .loading
imageLabelControl.isHighlighted = true
imageLabelControl.animate()
API().postComments(postToken: .id(post.id))
.execute()
.done { [weak self] (config, comments) in
guard
let `self` = self,
let updatedIndexPath = self.collectionViewDataSource.indexPath(
forItem: item
)
else { return }
item.state = .expanded
imageLabelControl.finishAnimation()
let nextIndexPath = IndexPath(
item: updatedIndexPath.row + 1,
section: updatedIndexPath.section
)
self.commentLoadSuccess(
post,
comments: comments,
indexPath: nextIndexPath,
cell: cell
)
}
.catch { _ in
item.state = .collapsed
imageLabelControl.finishAnimation()
cell.cancelCommentLoading()
}
}
}
func deleteCommentButtonTapped(cell: UICollectionViewCell) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard let indexPath = collectionView.indexPath(for: cell) else { return }
let message = InterfaceString.Post.DeleteCommentConfirm
let alertController = AlertViewController(message: message)
let yesAction = AlertAction(title: InterfaceString.Yes, style: .dark) { action in
guard let comment = self.collectionViewDataSource.comment(at: indexPath) else { return }
postNotification(CommentChangedNotification, value: (comment, .delete))
ContentChange.updateCommentCount(comment, delta: -1)
PostService().deleteComment(comment.postId, commentId: comment.id)
.done {
Tracker.shared.commentDeleted(comment)
}.ignoreErrors()
}
let noAction = AlertAction(title: InterfaceString.No, style: .light, handler: .none)
alertController.addAction(yesAction)
alertController.addAction(noAction)
responderChainable?.controller?.present(alertController, animated: true, completion: nil)
}
func editCommentButtonTapped(cell: UICollectionViewCell) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard
let indexPath = collectionView.indexPath(for: cell),
let comment = collectionViewDataSource.comment(at: indexPath),
let presentingController = responderChainable?.controller
else { return }
let responder: CreatePostResponder? = self.findProperResponder()
responder?.editComment(comment, fromController: presentingController)
}
func lovesButtonTapped(cell: StreamFooterCell) {
guard
let indexPath = collectionView.indexPath(for: cell),
let post = collectionViewDataSource.post(at: indexPath)
else { return }
toggleLove(cell, post: post, via: "button")
}
func lovesButtonTapped(post: Post) {
toggleLove(nil, post: post, via: "button")
}
func toggleLove(_ cell: LoveableCell?, post: Post, via: String) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
cell?.toggleLoveState(loved: !post.isLoved)
cell?.toggleLoveControl(enabled: false)
if post.isLoved { unlovePost(post, cell: cell) }
else { lovePost(post, cell: cell, via: via) }
}
private func unlovePost(_ post: Post, cell: LoveableCell?) {
Tracker.shared.postUnloved(post)
post.isLoved = false
if let count = post.lovesCount {
post.lovesCount = count - 1
}
ElloLinkedStore.shared.setObject(post, forKey: post.id, type: .postsType)
postNotification(PostChangedNotification, value: (post, .loved))
if let user = currentUser, let userLoveCount = user.lovesCount {
user.lovesCount = userLoveCount - 1
ElloLinkedStore.shared.setObject(user, forKey: user.id, type: .usersType)
postNotification(CurrentUserChangedNotification, value: user)
}
LovesService().unlovePost(postId: post.id)
.done { _ in
guard let currentUser = self.currentUser else { return }
let love = Love(
id: "",
isDeleted: true,
postId: post.id,
userId: currentUser.id
)
postNotification(ModelChangedNotification, value: (love, .delete))
}
.ensure {
cell?.toggleLoveControl(enabled: true)
}
.ignoreErrors()
}
private func lovePost(_ post: Post, cell: LoveableCell?, via: String) {
Tracker.shared.postLoved(post, via: via)
post.isLoved = true
if let count = post.lovesCount {
post.lovesCount = count + 1
}
ElloLinkedStore.shared.setObject(post, forKey: post.id, type: .postsType)
postNotification(PostChangedNotification, value: (post, .loved))
if let user = currentUser, let userLoveCount = user.lovesCount {
user.lovesCount = userLoveCount + 1
ElloLinkedStore.shared.setObject(user, forKey: user.id, type: .usersType)
postNotification(CurrentUserChangedNotification, value: user)
}
postNotification(HapticFeedbackNotifications.successfulUserEvent, value: ())
LovesService().lovePost(postId: post.id)
.done { love in
postNotification(ModelChangedNotification, value: (love, .create))
}
.ensure {
cell?.toggleLoveControl(enabled: true)
}
.ignoreErrors()
}
func repostButtonTapped(cell: UICollectionViewCell) {
guard
let indexPath = collectionView.indexPath(for: cell),
let post = collectionViewDataSource.post(at: indexPath)
else { return }
repostButtonTapped(post: post)
}
func repostButtonTapped(post: Post, presentingController presenter: UIViewController? = nil) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard let presentingController = presenter ?? responderChainable?.controller else { return }
Tracker.shared.postReposted(post)
let message = InterfaceString.Post.RepostConfirm
let alertController = AlertViewController(message: message)
alertController.shouldAutoDismiss = false
let yesAction = AlertAction(title: InterfaceString.Yes, style: .dark) { action in
self.createRepost(post, alertController: alertController)
}
let noAction = AlertAction(title: InterfaceString.No, style: .light) { action in
alertController.dismiss()
}
alertController.addAction(yesAction)
alertController.addAction(noAction)
presentingController.present(alertController, animated: true, completion: nil)
}
private func createRepost(_ post: Post, alertController: AlertViewController) {
alertController.resetActions()
alertController.isDismissable = false
let spinnerContainer = Container(
frame: CGRect(x: 0, y: 0, width: alertController.view.frame.size.width, height: 200)
)
let spinner = GradientLoadingView(
frame: CGRect(origin: .zero, size: GradientLoadingView.Size.size)
)
spinner.center = spinnerContainer.bounds.center
spinnerContainer.addSubview(spinner)
alertController.contentView = spinnerContainer
spinner.startAnimating()
if let user = currentUser, let userPostsCount = user.postsCount {
user.postsCount = userPostsCount + 1
postNotification(CurrentUserChangedNotification, value: user)
}
post.isReposted = true
if let repostsCount = post.repostsCount {
post.repostsCount = repostsCount + 1
}
else {
post.repostsCount = 1
}
ElloLinkedStore.shared.setObject(post, forKey: post.id, type: .postsType)
postNotification(PostChangedNotification, value: (post, .reposted))
RePostService().repost(post: post)
.done { repost in
postNotification(PostChangedNotification, value: (repost, .create))
postNotification(HapticFeedbackNotifications.successfulUserEvent, value: ())
alertController.contentView = nil
alertController.message = InterfaceString.Post.RepostSuccess
delay(1) {
alertController.dismiss()
}
}
.catch { _ in
alertController.contentView = nil
alertController.message = InterfaceString.Post.RepostError
alertController.shouldAutoDismiss = true
alertController.isDismissable = true
let okAction = AlertAction(title: InterfaceString.OK, style: .light, handler: .none)
alertController.addAction(okAction)
}
}
func shareButtonTapped(cell: UICollectionViewCell, sourceView: UIView) {
guard
let indexPath = collectionView.indexPath(for: cell),
let post = collectionViewDataSource.post(at: indexPath)
else { return }
shareButtonTapped(post: post, sourceView: sourceView)
}
func shareButtonTapped(
post: Post,
sourceView: UIView,
presentingController presenter: UIViewController? = nil
) {
guard
let shareLink = post.shareLink,
let shareURL = URL(string: shareLink),
let presentingController = presenter ?? responderChainable?.controller
else { return }
Tracker.shared.postShared(post)
let activityVC = UIActivityViewController(
activityItems: [shareURL],
applicationActivities: [SafariActivity()]
)
if UI_USER_INTERFACE_IDIOM() == .phone {
activityVC.modalPresentationStyle = .fullScreen
presentingController.present(activityVC, animated: true) {}
}
else {
activityVC.modalPresentationStyle = .popover
activityVC.popoverPresentationController?.sourceView = sourceView
presentingController.present(activityVC, animated: true) {}
}
}
func flagCommentButtonTapped(cell: UICollectionViewCell) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard
let indexPath = collectionView.indexPath(for: cell),
let comment = collectionViewDataSource.comment(at: indexPath),
let presentingController = responderChainable?.controller
else { return }
let flagger = ContentFlagger(
presentingController: presentingController,
flaggableId: comment.id,
contentType: .comment,
commentPostId: comment.postId
)
flagger.displayFlaggingSheet()
}
func replyToCommentButtonTapped(cell: UICollectionViewCell) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard
let indexPath = collectionView.indexPath(for: cell),
let comment = collectionViewDataSource.comment(at: indexPath),
let presentingController = responderChainable?.controller,
let atName = comment.author?.atName
else { return }
let postId = comment.loadedFromPostId
let responder: CreatePostResponder? = self.findProperResponder()
responder?.createComment(postId, text: "\(atName) ", fromController: presentingController)
}
func replyToAllButtonTapped(cell: UICollectionViewCell) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard
let indexPath = collectionView.indexPath(for: cell),
let comment = collectionViewDataSource.comment(at: indexPath),
let presentingController = responderChainable?.controller
else { return }
let postId = comment.loadedFromPostId
PostService().loadReplyAll(postId)
.done { [weak self] usernames in
guard let `self` = self else { return }
let usernamesText = usernames.reduce("") { memo, username in
return memo + "@\(username) "
}
let responder: CreatePostResponder? = self.findProperResponder()
responder?.createComment(
postId,
text: usernamesText,
fromController: presentingController
)
}
.catch { [weak self] error in
guard let `self` = self else { return }
guard let controller = self.responderChainable?.controller else { return }
let responder: CreatePostResponder? = self.findProperResponder()
responder?.createComment(postId, text: nil, fromController: controller)
}
}
func watchPostTapped(_ isWatching: Bool, cell: StreamCreateCommentCell) {
guard currentUser != nil else {
postNotification(LoggedOutNotifications.userActionAttempted, value: .postTool)
return
}
guard
let indexPath = collectionView.indexPath(for: cell),
let comment = collectionViewDataSource.comment(at: indexPath),
let post = comment.parentPost
else { return }
cell.isWatching = isWatching
cell.isUserInteractionEnabled = false
PostService().toggleWatchPost(post, isWatching: isWatching)
.done { post in
cell.isUserInteractionEnabled = true
if isWatching {
Tracker.shared.postWatched(post)
}
else {
Tracker.shared.postUnwatched(post)
}
postNotification(PostChangedNotification, value: (post, .watching))
}
.catch { error in
cell.isUserInteractionEnabled = true
cell.isWatching = !isWatching
}
}
private func commentLoadSuccess(
_ post: Post,
comments jsonables: [Model],
indexPath: IndexPath,
cell: StreamFooterCell
) {
let createCommentNow = jsonables.count == 0
self.appendCreateCommentItem(post, at: indexPath)
var items = StreamCellItemParser().parse(
jsonables,
streamKind: StreamKind.following,
currentUser: currentUser
)
if let lastComment = jsonables.last,
let postCommentsCount = post.commentsCount,
postCommentsCount > jsonables.count
{
items.append(StreamCellItem(jsonable: lastComment, type: .seeMoreComments))
}
else {
items.append(StreamCellItem(type: .spacer(height: 10.0)))
}
streamViewController.insertUnsizedCellItems(items, startingIndexPath: indexPath) {
[weak self] in
guard let `self` = self else { return }
cell.comments.isEnabled = true
if let controller = self.responderChainable?.controller,
createCommentNow,
self.currentUser != nil
{
let responder: CreatePostResponder? = self.findProperResponder()
responder?.createComment(post.id, text: nil, fromController: controller)
}
}
}
private func appendCreateCommentItem(_ post: Post, at indexPath: IndexPath) {
guard let currentUser = currentUser else { return }
let comment = ElloComment.newCommentForPost(post, currentUser: currentUser)
let createCommentItem = StreamCellItem(jsonable: comment, type: .createComment)
let items = [createCommentItem]
streamViewController.insertUnsizedCellItems(items, startingIndexPath: indexPath)
}
}
| mit | 9d6940217aaee55d897775992f71b985 | 36.350719 | 100 | 0.614244 | 5.413712 | false | false | false | false |
LegACy99/Project-Tube-Swift | Project Tube/src/GameViewController.swift | 1 | 5857 | //
// GameViewController.swift
// Project Tube
//
// Created by LegACy on 6/22/14.
// Copyright (c) 2014 Raka Mahesa. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController, SCNSceneRendererDelegate {
override func viewDidLoad() {
//Super
super.viewDidLoad()
//Initialize
m_State = StateGame();
m_Touches = [ TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo(), TouchInfo() ];
let GameView = self.view as SCNView;
//Configure scene view
GameView.scene = m_State!.getScene();
GameView.backgroundColor = UIColor.cyanColor();
GameView.multipleTouchEnabled = true;
GameView.showsStatistics = true;
GameView.delegate = self;
//Add touch handler
/*let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:");
let gestureRecognizers = NSMutableArray();
gestureRecognizers.addObject(tapGesture);
gestureRecognizers.addObjectsFromArray(GameView.gestureRecognizers);
GameView.gestureRecognizers = gestureRecognizers;*/
}
func handleTap(gestureRecognize: UIGestureRecognizer) {
// retrieve the SCNView
let scnView = self.view as SCNView
// check what nodes are tapped
let p = gestureRecognize.locationInView(scnView)
let hitResults = scnView.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject! = hitResults[0]
// get its material
let material = result.node!.geometry.firstMaterial
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material.emission.contents = UIColor.blackColor()
SCNTransaction.commit()
}
material.emission.contents = UIColor.redColor()
SCNTransaction.commit()
}
}
func findTouchInfo(touch:UITouch, save:Bool = false) -> TouchInfo? {
//Initialize
var Result: TouchInfo? = nil;
//If exist
if (touch != nil) {
//Get touch info
Result = m_UITouches[touch];
if (Result == nil) {
//For all info
for Info in m_Touches {
//If no result
if (Result == nil) {
//Check if current info is recording other touch
var Found = false;
for Saved in m_UITouches.values {
//If the same, than current info is already used
if (Found == false && Info === Saved) { Found = true; }
}
//If not found
if (!Found) {
//Save
Result = Info;
if (save) { m_UITouches[touch] = Result; }
}
}
}
}
}
//Return
return Result;
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
//For each touch
let Touches: AnyObject[] = touches.allObjects;
for Touch in Touches as UITouch[] {
//Get touch info
let Info = findTouchInfo(Touch, save: true);
if (Info != nil) {
//Press
let Location = Touch.locationInView(self.view);
Info!.pressed(Float(Location.x), y: Float(Location.y));
}
}
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
//For each touch
let Touches: AnyObject[] = touches.allObjects;
for Touch in Touches as UITouch[] {
//Get touch info
let Info = findTouchInfo(Touch);
if (Info != nil) {
//Move
let Location = Touch.locationInView(self.view);
Info!.dragged(Float(Location.x), y: Float(Location.y));
}
}
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
//For each touch
let Touches: AnyObject[] = touches.allObjects;
for Touch in Touches as UITouch[] {
//Get touch info
let Info = findTouchInfo(Touch);
if (Info != nil) {
//Release
let Location = Touch.locationInView(self.view);
Info!.released(Float(Location.x), y: Float(Location.y));
//Remove
m_UITouches.removeValueForKey(Touch);
}
}
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
//End
touchesEnded(touches, withEvent: event);
}
func renderer(renderer:SCNSceneRenderer, updateAtTime current:NSTimeInterval) {
//If there's a previous frame
if (m_LastTime >= 0) {
//Update with delta
let Delta = (Int)((current - m_LastTime) * 1000.0);
m_State!.update(Delta, touches: m_Touches);
}
//For all touch
for Touch in m_Touches {
//Manage touches
if (!Touch.isPressed() && Touch.wasPressed()) { Touch.removed(); }
else if (Touch.isPressed() && !Touch.wasPressed()) { Touch.dragged(Touch.getStartX(), y: Touch.getStartY()); }
}
//Save time
m_LastTime = current;
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
} else {
return Int(UIInterfaceOrientationMask.All.toRaw())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
//Class member
var m_State: StateGame? = nil;
var m_Touches: TouchInfo[] = [];
var m_UITouches: Dictionary<UITouch, TouchInfo> = [:];
var m_LastTime: NSTimeInterval = -1;
}
| mit | 96c36ca265d5c9b0907882ee19317164 | 28.285 | 148 | 0.620966 | 4.067361 | false | false | false | false |
m3rkus/Mr.Weather | Mr.Weather/JsonToObjMapper.swift | 1 | 5416 | //
// JsonToObjMapper.swift
// Mr.Weather
//
// Created by Роман Анистратенко on 12/09/2017.
// Copyright © 2017 m3rk edge. All rights reserved.
//
import Foundation
// MARK: Properties & init
class JsonToObjMapper {
fileprivate enum Keys: String {
case city = "name"
case weathers = "list"
case timestamp = "dt"
case weatherConditions = "weather"
case description = "description"
case mainInfo = "main"
case temperature = "temp"
case pressure = "pressure"
case humidity = "humidity"
case visibility = "visibility"
case windInfo = "wind"
case windSpeed = "speed"
case windDegree = "deg"
case cloudsInfo = "clouds"
case cloudCoverage = "all"
case otherInfo = "sys"
case sunrise = "sunrise"
case sunset = "sunset"
}
}
// MARK: Public
extension JsonToObjMapper {
func mapTodayWeatherData(json: [String: Any]) -> (WeatherInfo, String)? {
guard
let city = json[Keys.city.rawValue] as? String,
let weathers = json[Keys.weatherConditions.rawValue] as? [Any],
let recentWeather = weathers[0] as? [String: Any],
let state = recentWeather[Keys.mainInfo.rawValue] as? String,
let specification = recentWeather[Keys.description.rawValue] as? String,
let mainInfo = json[Keys.mainInfo.rawValue] as? [String: Double],
let temperature = mainInfo[Keys.temperature.rawValue],
let pressure = mainInfo[Keys.pressure.rawValue],
let humidity = mainInfo[Keys.humidity.rawValue],
let visibility = json[Keys.visibility.rawValue] as? Int,
let windInfo = json[Keys.windInfo.rawValue] as? [String: Double],
let windSpeed = windInfo[Keys.windSpeed.rawValue],
let windDegree = windInfo[Keys.windDegree.rawValue],
let clouds = json[Keys.cloudsInfo.rawValue] as? [String: Int],
let cloudCoverage = clouds[Keys.cloudCoverage.rawValue],
let other = json[Keys.otherInfo.rawValue] as? [String: Any],
let sunriseUnixTimestamp = other[Keys.sunrise.rawValue] as? Double,
let sunsetUnixTimestamp = other[Keys.sunset.rawValue] as? Double
else {
return nil
}
let mainWeatherInfo = MainWeatherInfo(
date: Date(),
temperature: temperature,
state: state,
windSpeed: windSpeed,
windDegree: windDegree)
let additionalWeatherInfo = AdditionalWeatherInfo(
specification: specification,
humidity: Helper.roundToInt(humidity),
pressure: Helper.roundToInt(pressure),
clouds: cloudCoverage,
visibility: visibility,
sunrise: Date(timeIntervalSince1970: sunriseUnixTimestamp),
sunset: Date(timeIntervalSince1970: sunsetUnixTimestamp))
return (WeatherInfo(main: mainWeatherInfo, additional: additionalWeatherInfo), city)
}
func mapWeekWeatherData(json: [String: Any]) -> [WeatherInfo]? {
var forecast = [WeatherInfo]()
let weekDates = self.getWeekDates()
guard let weathers = json[Keys.weathers.rawValue] as? [[String: Any]] else { return nil }
for weather in weathers {
if let timestamp = weather[Keys.timestamp.rawValue] as? Double {
let weatherDate = Date(timeIntervalSince1970: timestamp)
if weekDates.contains(weatherDate) {
guard
let mainInfo = weather[Keys.mainInfo.rawValue] as? [String: Double],
let temperature = mainInfo[Keys.temperature.rawValue],
let weatherDescriptions = weather[Keys.weatherConditions.rawValue] as? [Any],
let weatherDescription = weatherDescriptions[0] as? [String: Any],
let state = weatherDescription[Keys.mainInfo.rawValue] as? String,
let windInfo = weather[Keys.windInfo.rawValue] as? [String: Double],
let windSpeed = windInfo[Keys.windSpeed.rawValue],
let windDegree = windInfo[Keys.windDegree.rawValue]
else {
return nil
}
let mainWeatherInfo = MainWeatherInfo(
date: weatherDate,
temperature: temperature,
state: state,
windSpeed: windSpeed,
windDegree: windDegree)
let weatherInfo = WeatherInfo(main: mainWeatherInfo, additional: nil)
forecast.append(weatherInfo)
}
}
}
return forecast
}
}
// MARK: Private
private extension JsonToObjMapper {
func getWeekDates() -> [Date] {
let secondsInDay = 86400
let todayDate = Date()
var weekDates = [Date]()
for day in 1...4 {
if let weekDate = Helper.setCustom(time: (TimeZone.init(abbreviation: "UTC")!, 15, 0, 0), for: todayDate + TimeInterval(secondsInDay * day)) {
weekDates.append(weekDate)
}
}
return weekDates
}
}
| mit | 7768425985edd50eb2eec32eddea86ed | 34.513158 | 154 | 0.576325 | 4.789707 | false | false | false | false |
mcomella/prox | Prox/Prox/PlaceCarousel/PlaceCarouselViewController.swift | 1 | 12780 | /* 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 UIKit
import MapKit
import QuartzCore
import EDSunriseSet
import Deferred
private let MAP_SPAN_DELTA = 0.05
private let MAP_LATITUDE_OFFSET = 0.015
private let ONE_DAY: TimeInterval = (60 * 60) * 24
protocol PlaceDataSource: class {
func nextPlace(forPlace place: Place) -> Place?
func previousPlace(forPlace place: Place) -> Place?
func numberOfPlaces() -> Int
func place(forIndex: Int) throws -> Place
}
protocol LocationProvider: class {
func getCurrentLocation() -> CLLocation?
}
struct PlaceDataSourceError: Error {
let message: String
}
class PlaceCarouselViewController: UIViewController {
fileprivate let MIN_SECS_BETWEEN_LOCATION_UPDATES: TimeInterval = 1
fileprivate var timeOfLastLocationUpdate: Date?
lazy var locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
return manager
}()
var places: [Place] = [Place]() {
didSet {
// TODO: how do we make sure the user wasn't interacting?
headerView.numberOfPlacesLabel.text = "\(places.count) place" + (places.count != 1 ? "s" : "")
placeCarousel.refresh()
if oldValue.count == 0 {
openClosestPlace()
}
}
}
// the top part of the background. Contains Number of Places, horizontal line & (soon to be) Current Location button
lazy var headerView: PlaceCarouselHeaderView = {
let view = PlaceCarouselHeaderView()
return view
}()
// View that will display the sunset and sunrise times
lazy var sunView: UIView = {
let view = UIView()
view.backgroundColor = Colors.carouselViewPlaceCardBackground
view.layer.shadowColor = UIColor.darkGray.cgColor
view.layer.shadowOpacity = 0.25
view.layer.shadowOffset = CGSize(width: 0, height: 2)
view.layer.shadowRadius = 2
return view
}()
// label displaying sunrise and sunset times
lazy var sunriseSetTimesLabel: UILabel = {
let label = UILabel()
label.textColor = Colors.carouselViewSunriseSetTimesLabelText
label.font = Fonts.carouselViewSunriseSetTimes
return label
}()
lazy var placeCarousel: PlaceCarousel = {
let carousel = PlaceCarousel()
carousel.delegate = self
carousel.dataSource = self
carousel.locationProvider = self
return carousel
}()
var sunriseSet: EDSunriseSet? {
didSet {
setSunriseSetTimes()
}
}
private func setSunriseSetTimes() {
let today = Date()
guard let sunriseSet = self.sunriseSet else {
return self.sunriseSetTimesLabel.text = nil
}
sunriseSet.calculateSunriseSunset(today)
guard let sunrise = sunriseSet.localSunrise(),
let sunset = sunriseSet.localSunset(),
let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian) else {
return self.sunriseSetTimesLabel.text = nil
}
let sunriseToday = updateDateComponents(dateComponents: sunrise, toDate: today, withCalendar: calendar)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
if let sunriseTime = calendar.date(from: sunriseToday),
sunriseTime > today {
let timeAsString = dateFormatter.string(from: sunriseTime)
return self.sunriseSetTimesLabel.text = "Sunrise is at \(timeAsString) today"
}
let sunsetToday = updateDateComponents(dateComponents: sunset, toDate: today, withCalendar: calendar)
if let sunsetTime = calendar.date(from: sunsetToday),
sunsetTime > today {
let timeAsString = dateFormatter.string(from: sunsetTime)
return self.sunriseSetTimesLabel.text = "Sunset is at \(timeAsString) today"
}
let tomorrow = today.addingTimeInterval(ONE_DAY)
sunriseSet.calculateSunriseSunset(tomorrow)
if let tomorrowSunrise = sunriseSet.localSunrise(),
let tomorrowSunriseTime = calendar.date(from: tomorrowSunrise) {
let timeAsString = dateFormatter.string(from: tomorrowSunriseTime)
self.sunriseSetTimesLabel.text = "Sunrise is at \(timeAsString) tomorrow"
} else {
self.sunriseSetTimesLabel.text = nil
}
}
private func updateDateComponents(dateComponents: DateComponents, toDate date: Date, withCalendar calendar: NSCalendar) -> DateComponents {
var newDateComponents = dateComponents
newDateComponents.day = calendar.component(NSCalendar.Unit.day, from: date)
newDateComponents.month = calendar.component(NSCalendar.Unit.month, from: date)
newDateComponents.year = calendar.component(NSCalendar.Unit.year, from: date)
return newDateComponents
}
override func viewDidLoad() {
super.viewDidLoad()
if let backgroundImage = UIImage(named: "map_background") {
self.view.backgroundColor = UIColor(patternImage: backgroundImage)
}
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [Colors.carouselViewBackgroundGradientStart.cgColor, Colors.carouselViewBackgroundGradientEnd.cgColor]
view.layer.insertSublayer(gradient, at: 0)
// add the views to the stack view
view.addSubview(headerView)
// setting up the layout constraints
var constraints = [headerView.topAnchor.constraint(equalTo: view.topAnchor),
headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
headerView.heightAnchor.constraint(equalToConstant: 150)]
view.addSubview(sunView)
constraints.append(contentsOf: [sunView.topAnchor.constraint(equalTo: headerView.bottomAnchor),
sunView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
sunView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
sunView.heightAnchor.constraint(equalToConstant: 90)])
// set up the subviews for the sunrise/set view
sunView.addSubview(sunriseSetTimesLabel)
constraints.append(sunriseSetTimesLabel.leadingAnchor.constraint(equalTo: sunView.leadingAnchor, constant: 20))
constraints.append(sunriseSetTimesLabel.topAnchor.constraint(equalTo: sunView.topAnchor, constant: 14))
headerView.numberOfPlacesLabel.text = "" // placeholder
view.addSubview(placeCarousel.carousel)
constraints.append(contentsOf: [placeCarousel.carousel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
placeCarousel.carousel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
placeCarousel.carousel.topAnchor.constraint(equalTo: sunView.bottomAnchor, constant: -35),
placeCarousel.carousel.heightAnchor.constraint(equalToConstant: 275)])
// apply the constraints
NSLayoutConstraint.activate(constraints, translatesAutoresizingMaskIntoConstraints: false)
}
func refreshLocation() {
if (CLLocationManager.hasLocationPermissionAndEnabled()) {
locationManager.requestLocation()
} else {
// requestLocation expected to be called on authorization status change.
locationManager.maybeRequestLocationPermission(viewController: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func openClosestPlace() {
guard places.count > 0 else {
return
}
openDetail(forPlace: places[0])
}
func openDetail(forPlace place: Place) {
// if we are already displaying a place detail, don't try and display another one
// places should be able to update beneath without affecting what the user currently sees
if let _ = self.presentedViewController {
return
}
let placeDetailViewController = PlaceDetailViewController(place: place)
placeDetailViewController.dataSource = self
placeDetailViewController.locationProvider = self
self.present(placeDetailViewController, animated: true, completion: nil)
}
}
extension PlaceCarouselViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
refreshLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Use last coord: we want to display where the user is now.
if var location = locations.last {
// In iOS9, didUpdateLocations can be unexpectedly called multiple
// times for a single `requestLocation`: we guard against that here.
let now = Date()
if timeOfLastLocationUpdate == nil ||
(now - MIN_SECS_BETWEEN_LOCATION_UPDATES) > timeOfLastLocationUpdate! {
timeOfLastLocationUpdate = now
if AppConstants.MOZ_LOCATION_FAKING {
// fake the location to Hilton Waikaloa Village, Kona, Hawaii
location = CLLocation(latitude: 19.9263136, longitude: -155.8868328)
}
updateLocation(manager, location: location)
}
}
}
private func updateLocation(_ manager: CLLocationManager, location: CLLocation) {
let coord = location.coordinate
FirebasePlacesDatabase().getPlaces(forLocation: location).upon(DispatchQueue.main) { places in
self.places = PlaceUtilities.sort(places: places.flatMap { $0.successResult() }, byDistanceFromLocation: location)
}
// if we're running in the simulator, find the timezone of the current coordinates and calculate the sunrise/set times for then
// this is so that, if we're simulating our location, we still get sunset/sunrise times
#if (arch(i386) || arch(x86_64))
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { placemarks, error in
if let placemark = placemarks?.first {
DispatchQueue.main.async() {
self.sunriseSet = EDSunriseSet(timezone: placemark.timeZone, latitude: coord.latitude, longitude: coord.longitude)
}
}
}
#else
sunriseSet = EDSunriseSet(timezone: NSTimeZone.local, latitude: coord.latitude, longitude: coord.longitude)
#endif
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// TODO: handle
print("lol-location \(error.localizedDescription)")
}
}
extension PlaceCarouselViewController: PlaceDataSource {
func nextPlace(forPlace place: Place) -> Place? {
guard let currentPlaceIndex = places.index(where: {$0 == place}),
currentPlaceIndex + 1 < places.endIndex else {
return nil
}
return places[places.index(after: currentPlaceIndex)]
}
func previousPlace(forPlace place: Place) -> Place? {
guard let currentPlaceIndex = places.index(where: {$0 == place}),
currentPlaceIndex > places.startIndex else {
return nil
}
return places[places.index(before: currentPlaceIndex)]
}
func numberOfPlaces() -> Int {
return places.count
}
func place(forIndex index: Int) throws -> Place {
guard index < places.endIndex,
index >= places.startIndex else {
throw PlaceDataSourceError(message: "There is no place at index: \(index)")
}
return places[index]
}
}
extension PlaceCarouselViewController: PlaceCarouselDelegate {
func placeCarousel(placeCarousel: PlaceCarousel, didSelectPlaceAtIndex index: Int) {
openDetail(forPlace: places[index])
}
}
extension PlaceCarouselViewController: LocationProvider {
func getCurrentLocation() -> CLLocation? {
return self.locationManager.location
}
}
| mpl-2.0 | 803d611626059fef4ece124cf21109e9 | 37.610272 | 143 | 0.656729 | 5.089606 | false | false | false | false |
samsymons/Photon | Photon/Renderers/DefaultRenderer.swift | 1 | 4870 | // DefaultRenderer.swift
// Copyright (c) 2017 Sam Symons
//
// 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
import simd
public final class DefaultRenderer: Renderer {
public var maximumDepth: Int = 10
private let defaultColor = PixelData.init(r: 255, g: 255, b: 255)
private let pixelBuffer: Buffer
private let camera: Camera
private let callbackQueue: DispatchQueue
public var renderingOptions: RenderingOptions
public var geometricObjects: [GeometricObject] = []
private var width: Int {
return renderingOptions.width
}
private var height: Int {
return renderingOptions.height
}
private let renderQueue = DispatchQueue(label: "com.photon.image-rendering", qos: .userInitiated, attributes: .concurrent, target: nil)
private let writeQueue = DispatchQueue(label: "com.photon.image-writing", qos: .userInitiated, attributes: [], target: nil)
private let renderGroup = DispatchGroup()
public init(renderingOptions: RenderingOptions) {
self.renderingOptions = renderingOptions
self.camera = renderingOptions.camera
self.callbackQueue = renderingOptions.callbackQueue
self.pixelBuffer = Buffer(width: renderingOptions.width, height: renderingOptions.height)
}
// MARK: - Renderer
@discardableResult public func load(file: URL) -> Bool {
return false
}
public func renderScene(_ sceneCompletion: @escaping RendererCompletion) {
guard geometricObjects.count > 0 else { sceneCompletion(nil); return }
for row in 0 ..< renderingOptions.height {
for column in 0 ..< renderingOptions.width {
renderingOptions.renderStatistics?.incrementPixelCounter()
renderQueue.async(group: renderGroup) {
let pixelValue = self.traceRayFor(x: column, y: row)
self.writeQueue.async(group: self.renderGroup) {
self.pixelBuffer[(row, column)] = pixelValue
}
}
}
}
renderGroup.notify(queue: callbackQueue) {
let image = Image.image(from: self.pixelBuffer.pixelData, width: self.width, height: self.height)
sceneCompletion(image)
}
}
public func trace(ray: Ray, depth: Int = 0) -> PixelData {
var intersectionColor: PixelData?
var closestHitPoint: Float = -Float.greatestFiniteMagnitude
var closestIntersection: Intersection?
for object in geometricObjects {
let intersection = object.intersection(with: ray)
if intersection.isHit, intersection.intersectionPoint.z > closestHitPoint, intersection.t > 0.001 {
closestHitPoint = intersection.intersectionPoint.z
closestIntersection = intersection
intersectionColor = intersection.material.color
}
}
if let intersection = closestIntersection, depth < maximumDepth {
let reflectionDirection = intersection.intersectionPoint + intersection.normal + MathUtilities.randomPointInsideUnitSphere()
let reflectedRay = Ray(origin: intersection.intersectionPoint, direction: reflectionDirection - intersection.intersectionPoint)
return trace(ray: reflectedRay, depth: depth + 1) * 0.5
} else {
return intersectionColor ?? defaultColor
}
}
// MARK: - Private Functions
@inline(__always) private func traceRayFor(x: Int, y: Int) -> PixelData {
guard renderingOptions.sampleAdditionalPoints else {
let ray = camera.castRayAt(x: Float(x), y: Float(y))
let color = trace(ray: ray, depth: 0)
return color
}
let points = renderingOptions.sampler.generateSampleBundle(at: Point2D(Float(x), Float(y)))
var sampleCollection = SampleColorCollection()
for point in points {
let ray = camera.castRayAt(x: point.x, y: point.y)
let color = trace(ray: ray, depth: 0)
sampleCollection.collect(color: color)
}
return sampleCollection.averagePixelValue()
}
}
| mit | c27cba4f8815375dcb3b5ac0c1f39f88 | 35.893939 | 137 | 0.723614 | 4.451554 | false | false | false | false |
gtranchedone/AlgorithmsSwift | Algorithms.playground/Pages/Problem - Group Anagrams.xcplaygroundpage/Contents.swift | 1 | 1220 | /*:
[Previous](@previous)
# Partition into anagrams
### The anagrams are in the input. For example, given the input Set [“debitcard”, “elvis”, “silent”, “badcredit”, “lives”, “freedom”, “listen”, “levis”], the algorithm should return the sets [“debitcard, “badcredit”], [“elvis, “lives”, “elvis”], [“silent”, “listen”]
*/
// O(N + MLogM) where N = input.count and M = input chars count
func groupAnagrams(input: Set<String>) -> [Set<String>] {
var dictionary = [String : Set<String>]()
for string in input {
let sortedValue = stringBySortingStringChars(string)
var set = dictionary[sortedValue] ?? Set<String>()
set.insert(string)
dictionary[sortedValue] = set
}
var anagrams = [Set<String>]()
for (_, set) in dictionary {
if set.count > 1 {
anagrams.append(set)
}
}
return anagrams
}
// O(NlogN)
func stringBySortingStringChars(s: String) -> String {
let chars = s.characters.sort(<)
return String(chars)
}
let set = Set<String>(arrayLiteral: "debitcard", "elvis", "silent", "badcredit", "lives", "freedom", "listen", "levis")
groupAnagrams(set)
//: [Next](@next) | mit | f25645e7a60d7afee6dc07d4fa74106f | 33.264706 | 266 | 0.630584 | 3.393586 | false | false | false | false |
zach-unbounded/MineSweeper | MineSweeper/MSGrid.swift | 1 | 1729 | //
// MSGrid.swift
// MineSweeper
//
// Created by Zachary Burgess on 01/12/2015.
// Copyright © 2015 V.Rei Ltd. All rights reserved.
//
import Foundation
class MSGrid {
private var grid : [[MSGridCell]]
init(){
grid = [[MSGridCell]](count: 0, repeatedValue: [MSGridCell](count: 0, repeatedValue: MSGridCell()))
}
convenience init(dimentions : Int) {
self.init()
self.setDimentions(dimentions)
}
func setDimentions(dimentions : Int) {
grid = [[MSGridCell]](count: dimentions, repeatedValue: [MSGridCell](count: dimentions, repeatedValue: MSGridCell()))
}
func updateCell(indexPath : NSIndexPath, state:GridCellState) -> Bool {
if grid.count > indexPath.top {
if grid[indexPath.top].count > indexPath.down {
let cell = grid[indexPath.top][indexPath.down]
cell.state = state
return true
}
}
return false
}
func cellAtIndex(indexPath : NSIndexPath) -> MSGridCell? {
return grid[indexPath.top][indexPath.down]
}
func cellsSeroundingIndex(indexPath : NSIndexPath) -> [MSGridCell] {
let cells = [MSGridCell]()
return cells
}
}
extension NSIndexPath {
public convenience init(top: Int, inDown down: Int) {
self.init()
var indexPath = self.indexPathByAddingIndex(top)
indexPath = indexPath.indexPathByAddingIndex(down)
}
public var top: Int {
get {
return self.indexAtPosition(0)
}
}
public var down: Int {
get {
return self.indexAtPosition(1)
}
}
} | gpl-3.0 | db8c2adfeea017b4587235a62d2a370b | 23.7 | 125 | 0.574653 | 4.235294 | false | false | false | false |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/PhysicsBody+Internal.swift | 1 | 1492 | //
// PhysicsBody+Internal.swift
// Fiber2D
//
// Created by Andrey Volodin on 20.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
internal func internalBodySetMass(_ body: UnsafeMutablePointer<cpBody>, _ mass: cpFloat)
{
cpBodyActivate(body);
body.pointee.m = mass;
body.pointee.m_inv = 1.0 / mass
//cpAssertSaneBody(body);
}
internal func internalBodyUpdateVelocity(_ body: UnsafeMutablePointer<cpBody>?, _ gravity: cpVect, _ damping: cpFloat, _ dt: cpFloat) {
cpBodyUpdateVelocity(body, cpvzero, damping, dt)
// Skip kinematic bodies.
guard cpBodyGetType(body) != CP_BODY_TYPE_KINEMATIC else {
return
}
let physicsBody = Unmanaged<PhysicsBody>.fromOpaque(cpBodyGetUserData(body)).takeUnretainedValue()
if physicsBody.isGravityEnabled {
body!.pointee.v = cpvclamp(cpvadd(cpvmult(body!.pointee.v, damping), cpvmult(cpvadd(gravity, cpvmult(body!.pointee.f, body!.pointee.m_inv)), dt)), cpFloat(physicsBody.velocityLimit))
} else {
body!.pointee.v = cpvclamp(cpvadd(cpvmult(body!.pointee.v, damping), cpvmult(cpvmult(body!.pointee.f, body!.pointee.m_inv), dt)), cpFloat(physicsBody.velocityLimit))
}
let w_limit = cpFloat(physicsBody.angularVelocityLimit)
body!.pointee.w = cpfclamp(body!.pointee.w * damping + body!.pointee.t * body!.pointee.i_inv * dt, -w_limit, w_limit)
// Reset forces.
body!.pointee.f = cpvzero
//to check body sanity
cpBodySetTorque(body, 0.0)
}
| apache-2.0 | 998a4979ad73cae65d1c0dcecda5117d | 38.236842 | 190 | 0.694165 | 3.365688 | false | false | false | false |
sivaganeshsg/MemeSon | MemeSon/ViewController.swift | 1 | 9731 | //
// ViewController.swift
// MemeSon
//
// Created by Siva Ganesh on 06/09/15.
// Copyright (c) 2015 Siva Ganesh. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var bottomToolbar: UIToolbar!
@IBOutlet weak var userGuide: UILabel!
@IBOutlet weak var userGuideImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tabBarController?.tabBar.hidden = true
defaultMemeTextDisappear()
defaultHideBtns()
subscribeToKeyboardNotification()
subscribeToKeyboardHideNotification()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
camButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
topText.delegate = topTextDelegate
bottomText.delegate = bottomTextDelegate
textChar()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
@IBOutlet weak var topText: UITextField!
@IBOutlet weak var bottomText: UITextField!
var topTextDelegate = TopTextDelegate()
var bottomTextDelegate = BottomTextDelegate()
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var camButton: UIBarButtonItem!
@IBOutlet weak var shareBtn: UIBarButtonItem!
@IBOutlet weak var saveBtn: UIBarButtonItem!
@IBAction func picImage(sender: UIBarButtonItem) {
let pickerCont = UIImagePickerController()
pickerCont.delegate = self
pickerCont.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(pickerCont, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let imgSelected = info[UIImagePickerControllerOriginalImage] as? UIImage {
let screenSize = UIScreen.mainScreen().bounds.size;
imgView.image = scaleUIImageToSize(imgSelected, size: screenSize)
imgView.autoresizingMask = [.FlexibleBottomMargin, .FlexibleHeight, .FlexibleRightMargin, .FlexibleLeftMargin, .FlexibleTopMargin, .FlexibleWidth ]
imgView.contentMode = UIViewContentMode.ScaleAspectFit
userGuide.hidden = true
userGuideImage.hidden = true
defaultMemeTextAppear()
shareBtn.enabled = true
// Disabled for Review Purpose.
// enableSaveBtn()
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func camImage(sender: UIBarButtonItem) {
let camCont = UIImagePickerController()
camCont.delegate = self
camCont.sourceType = UIImagePickerControllerSourceType.Camera
presentViewController(camCont, animated: true, completion: nil)
}
var savedImg : UIImage?
@IBAction func saveMeme(sender: UIBarButtonItem) {
saveMemeFn()
}
@IBAction func shareMeme(sender: AnyObject) {
savedImg = generateMemedImage()
if let img = savedImg{
let title = topText.text!
let avCont = UIActivityViewController(activityItems: [title, img], applicationActivities: nil)
presentViewController(avCont, animated: true, completion: {
self.saveMemeFn()
})
}
}
@IBAction func memeModel(sender: AnyObject) {
var memes: [Meme] {
return (UIApplication.sharedApplication().delegate as! AppDelegate).memes
}
}
// MARK : Helper Functions
func saveMemeFn(){
let newImg = generateMemedImage()
//Create the meme
let meme = Meme( text1: topText.text!, text2: bottomText.text!, image: imgView.image!, newImage: newImg)
// Add it to the memes array in the Application Delegate
let object = UIApplication.sharedApplication().delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
imgView.image = newImg
defaultMemeTextDisappear()
}
func disableSaveBtn(){
saveBtn.enabled = false
}
func enableSaveBtn(){
saveBtn.enabled = true
}
func textChar(){
let memeTextAttributes = [
NSStrokeColorAttributeName : UIColor.blackColor(),
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : "-5.2"
]
topText.defaultTextAttributes = memeTextAttributes
bottomText.defaultTextAttributes = memeTextAttributes
topText.textAlignment = .Center
bottomText.textAlignment = .Center
}
func defaultMemeTextDisappear(){
topText.hidden = true
bottomText.hidden = true
}
func defaultMemeTextAppear(){
topText.hidden = false
bottomText.hidden = false
}
func defaultHideBtns(){
shareBtn.enabled = false
saveBtn.enabled = false
}
func generateMemedImage() -> UIImage
{
// Hiding toolbar and navbar
bottomToolbar.hidden = true
navigationController?.navigationBarHidden = true
// Render view to an image
UIGraphicsBeginImageContext(view.frame.size)
view.drawViewHierarchyInRect(view.frame,
afterScreenUpdates: true)
let memedImage : UIImage =
UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Showing toolbar and navbar
bottomToolbar.hidden = false
navigationController?.navigationBarHidden = false
return memedImage
}
/* From http://nshipster.com/image-resizing/ */
func scaleUIImageToSize(let image: UIImage, let size: CGSize) -> UIImage {
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
// NSNotifications
// Mark : Move Keyboard
func subscribeToKeyboardNotification(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification){
// Note : Swift 2 - weird issue with getKeyBoardHeight
// view.frame.origin.y -= getKeyboardHeight(notification)
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.height - keyboardSize.height)
}
// Alternate
/*
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
view.frame.origin.y -= keyboardSize.height
print(view.frame.origin.y)
print(keyboardSize.height)
}
*/
disableSaveBtn()
}
/*
Note : Swift 1.2 code. Not using now.
func getKeyboardHeight(notification: NSNotification) -> CGFloat{
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
*/
func unsubscribeToKeyboardNotification(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
}
// Move the pic back to bottom
func subscribeToKeyboardHideNotification(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillHide(notification: NSNotification){
// Note : Swift 2 - weird issue with getKeyBoardHeight
// view.frame.origin.y += getKeyboardHeight(notification)
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, UIScreen.mainScreen().bounds.size.height)
// Alternate
/*
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
view.frame.origin.y += keyboardSize.height
}
*/
// Disabled for Review
// enableSaveBtn()
}
func unsubscribeToKeyboardHideNotification(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
}
| mit | 9c00615361902f19b64c4651c980f6d9 | 28.134731 | 159 | 0.628507 | 5.984625 | false | false | false | false |
KevinCoble/Convolution | Source/Convolution/DeepNeuralNetworkController.swift | 1 | 6259 | //
// DeepNeuralNetworkController
// Convolution
//
// Created by Kevin Coble on 2/21/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Cocoa
import AIToolbox
class DeepNeuralNetworkController: NSViewController {
@IBOutlet weak var activationFunctionPopup: NSPopUpButton!
@IBOutlet weak var outputShapeBox: NSBox!
@IBOutlet weak var oneDOutputRadioButton: NSButton!
@IBOutlet weak var twoDOutputRadioButton: NSButton!
@IBOutlet weak var threeDOutputRadioButton: NSButton!
@IBOutlet weak var fourDOutputRadioButton: NSButton!
@IBOutlet weak var node1TextField: NSTextField!
@IBOutlet weak var node2TextField: NSTextField!
@IBOutlet weak var node3TextField: NSTextField!
@IBOutlet weak var node4TextField: NSTextField!
@IBOutlet weak var node1Stepper: NSStepper!
@IBOutlet weak var node2Stepper: NSStepper!
@IBOutlet weak var node3Stepper: NSStepper!
@IBOutlet weak var node4Stepper: NSStepper!
// Inputs
var activationOnly = false
var dimension = 2
var numNodes = [16, 16, 1, 1]
var activation = NeuralActivationFunction.sigmoid
var editSize : DeepChannelSize?
var addingInput = false
override func viewDidLoad() {
super.viewDidLoad()
// Set the initial values into the dialog
activationFunctionPopup.selectItem(withTag: activation.rawValue)
if (activationOnly) {
outputShapeBox.isHidden = true
}
else {
if let editSize = editSize {
switch (editSize.numDimensions) {
case 1:
onDimensionChange(oneDOutputRadioButton)
case 2:
onDimensionChange(twoDOutputRadioButton)
case 3:
onDimensionChange(threeDOutputRadioButton)
case 4:
onDimensionChange(fourDOutputRadioButton)
default:
break
}
setFromResultSize(editSize)
}
}
}
func setFromResultSize(_ size: DeepChannelSize)
{
// Set the radio button selection
var selectButton = oneDOutputRadioButton
dimension = size.numDimensions
if (dimension == 2) { selectButton = twoDOutputRadioButton }
if (dimension == 3) { selectButton = threeDOutputRadioButton }
if (dimension == 4) { selectButton = fourDOutputRadioButton }
selectButton?.state = NSOnState
// Set the node size amounts
node1TextField.integerValue = size.dimensions[0]
node1Stepper.integerValue = size.dimensions[0]
if (dimension > 1) {
node2TextField.integerValue = size.dimensions[1]
node2Stepper.integerValue = size.dimensions[1]
}
if (dimension > 2) {
node3TextField.integerValue = size.dimensions[2]
node3Stepper.integerValue = size.dimensions[2]
}
if (dimension > 3) {
node4TextField.integerValue = size.dimensions[3]
node4Stepper.integerValue = size.dimensions[3]
}
}
@IBAction func onDimensionChange(_ sender: NSButton) {
// Get the dimension from the radio button tag
dimension = sender.tag
if (dimension < 4) {
node4TextField.integerValue = 1
node4Stepper.integerValue = 1
node4TextField.isEnabled = false
node4Stepper.isEnabled = false
}
else {
node4TextField.isEnabled = true
node4Stepper.isEnabled = true
}
if (dimension < 3) {
node3TextField.integerValue = 1
node3Stepper.integerValue = 1
node3TextField.isEnabled = false
node3Stepper.isEnabled = false
}
else {
node3TextField.isEnabled = true
node3Stepper.isEnabled = true
}
if (dimension < 2) {
node2TextField.integerValue = 1
node2Stepper.integerValue = 1
node2TextField.isEnabled = false
node2Stepper.isEnabled = false
}
else {
node2TextField.isEnabled = true
node2Stepper.isEnabled = true
}
}
@IBAction func onNode1TextFieldChanged(_ sender: NSTextField) {
node1Stepper.integerValue = node1TextField.integerValue
}
@IBAction func onNode1StepperChanged(_ sender: NSStepper) {
node1TextField.integerValue = node1Stepper.integerValue
}
@IBAction func onNode2TextFieldChanged(_ sender: NSTextField) {
node2Stepper.integerValue = node2TextField.integerValue
}
@IBAction func onNode2StepperChanged(_ sender: NSStepper) {
node2TextField.integerValue = node2Stepper.integerValue
}
@IBAction func onNode3TextFieldChanged(_ sender: NSTextField) {
node3Stepper.integerValue = node3TextField.integerValue
}
@IBAction func onNode3StepperChanged(_ sender: NSStepper) {
node3TextField.integerValue = node3Stepper.integerValue
}
@IBAction func onNode4TextFieldChanged(_ sender: NSTextField) {
node4Stepper.integerValue = node4TextField.integerValue
}
@IBAction func onNode4StepperChanged(_ sender: NSStepper) {
node4TextField.integerValue = node4Stepper.integerValue
}
@IBAction func onCancel(_ sender: NSButton) {
presenting?.dismissViewController(self)
}
@IBAction func onOK(_ sender: NSButton) {
let networkVC = presenting as! NetworkViewController
activation = NeuralActivationFunction(rawValue: activationFunctionPopup.selectedTag())!
if (activationOnly) {
networkVC.nonLinearityEditComplete(activation: activation)
}
else {
numNodes[0] = node1TextField.integerValue
numNodes[1] = node2TextField.integerValue
numNodes[2] = node3TextField.integerValue
numNodes[3] = node4TextField.integerValue
networkVC.neuralNetworkEditComplete(dimension, numNodes: numNodes, activation: activation)
}
presenting?.dismissViewController(self)
}
}
| apache-2.0 | b1fa70657a8748503d07d3f38af5906d | 33.766667 | 102 | 0.633269 | 4.962728 | false | false | false | false |
IamAlchemist/DemoDynamicCollectionView | DemoDynamicCollectionView/Photo.swift | 1 | 1627 | //
// Photo.swift
// DemoDynamicCollectionView
//
// Created by wizard on 1/14/16.
// Copyright © 2016 morgenworks. All rights reserved.
//
import UIKit
class Photo {
var caption : String
var comment : String
var image : UIImage
init(caption: String, comment: String, image: UIImage) {
self.caption = caption
self.comment = comment
self.image = image
}
convenience init(dictionary: NSDictionary){
let caption = dictionary["Caption"] as! String
let comment = dictionary["Comment"] as! String
let photo = dictionary["Photo"] as! String
let image = UIImage(named: photo)
self.init(caption: caption, comment: comment, image: image!)
}
func heightForComment(font: UIFont, width: CGFloat) -> CGFloat {
let rect = NSString(string: comment).boundingRectWithSize(
CGSize(width: width, height: CGFloat(MAXFLOAT)),
options: .UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil)
return ceil(rect.height)
}
class func allPhotos() -> [Photo] {
var photos = [Photo]()
guard let URL = NSBundle.mainBundle()
.URLForResource("Photos", withExtension: "plist")
else { return photos }
guard let photosFromPlist = NSArray(contentsOfURL: URL)
else { return photos }
for dictionary in photosFromPlist {
photos.append(Photo(dictionary: dictionary as! NSDictionary))
}
return photos
}
}
| mit | 26d66179fa108fdbf591460d21f278cd | 28.035714 | 73 | 0.595326 | 4.839286 | false | false | false | false |
kaltura/playkit-ios | Classes/Models/PKBoundary.swift | 1 | 2636 | // ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
/// `PKBoundary` used as abstract for boundary types (% and time).
@objc public protocol PKBoundary {
var time: TimeInterval { get }
}
/// `PKBoundaryFactory` factory class used to create boundary objects easily.
@objc public class PKBoundaryFactory: NSObject {
let duration: TimeInterval
@objc public init (duration: TimeInterval) {
self.duration = duration
}
@objc public func percentageTimeBoundary(boundary: Int) -> PKPercentageTimeBoundary {
return PKPercentageTimeBoundary(boundary: boundary, duration: self.duration)
}
@objc public func timeBoundary(boundaryTime: TimeInterval) -> PKTimeBoundary {
return PKTimeBoundary(boundaryTime: boundaryTime, duration: self.duration)
}
}
/// `PKPercentageTimeBoundary` represents a time boundary in % against the media duration.
@objc public class PKPercentageTimeBoundary: NSObject, PKBoundary {
/// The time to set the boundary on.
public let time: TimeInterval
/// Creates a new `PKPercentageTimeBoundary` object from %.
/// - Attention: boundary value should be between 1 and 100 otherwise will use default values!
@objc public init(boundary: Int, duration: TimeInterval) {
switch boundary {
case 1...100: self.time = duration * TimeInterval(boundary) / TimeInterval(100)
case Int.min...0: self.time = 0
case 101...Int.max: self.time = duration
default: self.time = 0
}
}
}
/// `PKTimeBoundary` represents a time boundary in seconds.
@objc public class PKTimeBoundary: NSObject, PKBoundary {
/// The time to set the boundary on.
@objc public let time: TimeInterval
/// Creates a new `PKTimeBoundary` object from seconds.
/// - Attention: boundary value should be between 0 and duration otherwise will use default values!
@objc public init(boundaryTime: TimeInterval, duration: TimeInterval) {
if boundaryTime <= 0 {
self.time = 0
} else if boundaryTime >= duration {
self.time = duration
} else {
self.time = boundaryTime
}
}
}
| agpl-3.0 | f05185ca0dea22c131cbd3667cd128b1 | 36.126761 | 103 | 0.625569 | 4.741007 | false | false | false | false |
hejunbinlan/Carlos | Sample/CappedRequestCacheSampleViewController.swift | 2 | 885 | import Foundation
import UIKit
import Carlos
class CappedRequestCacheSampleViewController: BaseCacheViewController {
private var cache: RequestCapperCache<BasicCache<NSURL, NSData>>!
private static let RequestsCap = 3
override func fetchRequested() {
super.fetchRequested()
let timestamp = NSDate().timeIntervalSince1970
self.eventsLogView.text = "\(self.eventsLogView.text)Request timestamp: \(timestamp)\n"
cache.get(NSURL(string: urlKeyField?.text ?? "")!)
.onSuccess { value in
self.eventsLogView.text = "\(self.eventsLogView.text)Request with timestamp \(timestamp) succeeded\n"
}
}
override func titleForScreen() -> String {
return "Capped cache"
}
override func setupCache() {
super.setupCache()
cache = capRequests(delayedNetworkCache(), CappedRequestCacheSampleViewController.RequestsCap)
}
} | mit | b40a25b6aec09c852bfaf4a265e046fb | 29.551724 | 109 | 0.723164 | 4.402985 | false | false | false | false |
rmavani/SocialQP | QPrint/Utility/Library/SLPopupViewController/UIVViewController-SLPopup.swift | 1 | 10871 |
//
// UIVViewController-SLpopup.swift
// AnonyChat
//
// Created by Nguyen Duc Hoang on 9/6/15.
// Copyright © 2015 Home. All rights reserved.
//
import UIKit
import QuartzCore
import ObjectiveC
enum SLpopupViewAnimationType: Int {
case BottomTop
case TopBottom
case BottomBottom
case TopTop
case LeftLeft
case LeftRight
case RightLeft
case RightRight
case Fade
}
let kSourceViewTag = 11111
let kpopupViewTag = 22222
let kOverlayViewTag = 22222
var kpopupViewController:UInt8 = 0
var kpopupBackgroundView:UInt8 = 1
let kpopupAnimationDuration = 0.35
let kSLViewDismissKey = "kSLViewDismissKey"
extension UIViewController {
var popupBackgroundView:UIView? {
get {
return objc_getAssociatedObject(self, &kpopupBackgroundView) as? UIView
}
set(newValue) {
objc_setAssociatedObject(self, &kpopupBackgroundView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var popupViewController:UIViewController? {
get {
return objc_getAssociatedObject(self, &kpopupViewController) as? UIViewController
}
set(newValue) {
objc_setAssociatedObject(self, &kpopupViewController, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// var dismissedCallback:UIViewController? {
// get {
// return objc_getAssociatedObject(self, kSLViewDismissKey) as? UIViewController
// }
// set(newValue) {
// objc_setAssociatedObject(self, kSLViewDismissKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// }
// }
func presentpopupViewController(popupViewController: UIViewController, animationType:SLpopupViewAnimationType, completion:() -> Void) {
let sourceView:UIView = self.getTopView()
self.popupViewController = popupViewController
let popupView:UIView = popupViewController.view
sourceView.tag = kSourceViewTag
popupView.autoresizingMask = [.flexibleTopMargin,.flexibleLeftMargin,.flexibleRightMargin,.flexibleBottomMargin]
popupView.tag = kpopupViewTag
if(sourceView.subviews.contains(popupView)) {
return
}
popupView.layer.shadowPath = UIBezierPath(rect: popupView.bounds).cgPath
// popupView.layer.masksToBounds = false
// popupView.layer.shadowOffset = CGSizeMake(5, 5)
// popupView.layer.shadowRadius = 5
// popupView.layer.shadowOpacity = 0.5
popupView.layer.shouldRasterize = true
popupView.layer.rasterizationScale = UIScreen.main.scale
let overlayView:UIView = UIView(frame: sourceView.bounds)
overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlayView.tag = kOverlayViewTag
overlayView.backgroundColor = UIColor.clear
self.popupBackgroundView = UIView(frame: sourceView.bounds)
self.popupBackgroundView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.popupBackgroundView!.backgroundColor = UIColor.black
self.popupBackgroundView?.alpha = 0.0
if let _ = self.popupBackgroundView {
overlayView.addSubview(self.popupBackgroundView!)
}
//Background is button
let dismissButton: UIButton = UIButton(type: .custom)
dismissButton.autoresizingMask = [.flexibleWidth, .flexibleHeight]
dismissButton.backgroundColor = UIColor.clear
dismissButton.frame = sourceView.bounds
overlayView.addSubview(dismissButton)
popupView.alpha = 0.0
overlayView.addSubview(popupView)
sourceView.addSubview(overlayView)
dismissButton.addTarget(self, action: #selector(UIViewController.btnDismissViewControllerWithAnimation(_:)), for: .touchUpInside)
switch animationType {
case .BottomTop, .BottomBottom,.TopTop,.TopBottom, .LeftLeft, .LeftRight,.RightLeft, .RightRight:
dismissButton.tag = animationType.rawValue
// print("slider1")
self.slideView(popupView: popupView, sourceView: sourceView, overlayView: overlayView, animationType: animationType)
default:
dismissButton.tag = SLpopupViewAnimationType.Fade.rawValue
self.fadeView(popupView: popupView, sourceView: sourceView, overlayView: overlayView)
}
}
func slideView(popupView: UIView, sourceView:UIView, overlayView:UIView, animationType: SLpopupViewAnimationType) {
let sourceSize: CGSize = sourceView.bounds.size
let popupSize: CGSize = popupView.bounds.size
var popupStartRect:CGRect
switch animationType {
case .BottomTop, .BottomBottom:
popupStartRect = CGRect(x: (sourceSize.width - popupSize.width)/2, y: sourceSize.height, width: popupSize.width, height: popupSize.height)
case .LeftLeft, .LeftRight:
popupStartRect = CGRect(x: -sourceSize.width, y: (sourceSize.height - popupSize.height)/2, width: popupSize.width, height: popupSize.height)
case .TopTop, .TopBottom:
popupStartRect = CGRect(x: (sourceSize.width - popupSize.width)/2, y: -sourceSize.height, width: popupSize.width, height: popupSize.height)
default:
popupStartRect = CGRect(x: sourceSize.width, y: (sourceSize.height - popupSize.height)/2, width: popupSize.width, height: popupSize.height)
}
let popupEndRect : CGRect = CGRect(x: (sourceSize.width - popupSize.width)/2, y: (sourceSize.height - popupSize.height)/2, width: popupSize.width, height: popupSize.height)
popupView.frame = popupStartRect
popupView.alpha = 1.0
UIView.animate(withDuration: kpopupAnimationDuration, animations: { () -> Void in
self.popupViewController?.viewWillAppear(false)
self.popupBackgroundView?.alpha = 0.5
popupView.frame = popupEndRect
}) { (finished) -> Void in
self.popupViewController?.viewDidAppear(false)
}
}
func slideViewOut(popupView: UIView, sourceView:UIView, overlayView:UIView, animationType: SLpopupViewAnimationType) {
let sourceSize: CGSize = sourceView.bounds.size
let popupSize: CGSize = popupView.bounds.size
var popupEndRect:CGRect
switch animationType {
case .BottomTop, .TopTop:
popupEndRect = CGRect(x: (sourceSize.width - popupSize.width)/2, y: -popupSize.height, width: popupSize.width, height: popupSize.height)
case .BottomBottom, .TopBottom:
popupEndRect = CGRect(x: (sourceSize.width - popupSize.width)/2, y: popupSize.height, width: popupSize.width, height: popupSize.height)
case .LeftRight, .RightRight:
popupEndRect = CGRect(x: sourceSize.width, y: popupView.frame.origin.y, width: popupSize.width, height: popupSize.height)
default:
popupEndRect = CGRect(x: -popupSize.width, y: popupView.frame.origin.y, width: popupSize.width, height: popupSize.height)
}
UIView.animate(withDuration: 0.2, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
self.popupBackgroundView?.backgroundColor = UIColor.clear
}) { (finished) -> Void in
UIView.animate(withDuration: kpopupAnimationDuration, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
self.popupViewController?.viewWillDisappear(false)
popupView.frame = popupEndRect
}) { (finished) -> Void in
popupView.removeFromSuperview()
overlayView.removeFromSuperview()
self.popupViewController?.viewDidDisappear(false)
self.popupViewController = nil
}
}
}
func fadeView(popupView: UIView, sourceView:UIView, overlayView:UIView) {
let sourceSize: CGSize = sourceView.bounds.size
let popupSize: CGSize = popupView.bounds.size
popupView.frame = CGRect(x: (sourceSize.width - popupSize.width)/2, y: (sourceSize.height - popupSize.height)/2, width: popupSize.width, height: popupSize.height)
popupView.alpha = 0.0
UIView.animate(withDuration: kpopupAnimationDuration, animations: { () -> Void in
self.popupViewController!.viewWillAppear(false)
self.popupBackgroundView!.alpha = 0.5
popupView.alpha = 1.0
}) { (finished) -> Void in
self.popupViewController?.viewDidAppear(false)
}
}
func fadeViewOut(popupView: UIView, sourceView:UIView, overlayView:UIView) {
UIView.animate(withDuration: kpopupAnimationDuration, animations: { () -> Void in
self.popupViewController?.viewDidDisappear(false)
self.popupBackgroundView?.alpha = 0.0
popupView.alpha = 0.0
}) { (finished) -> Void in
popupView.removeFromSuperview()
overlayView.removeFromSuperview()
self.popupViewController?.viewDidDisappear(false)
self.popupViewController = nil
}
}
func btnDismissViewControllerWithAnimation(_ btnDismiss : UIButton) {
let animationType:SLpopupViewAnimationType = SLpopupViewAnimationType(rawValue: btnDismiss.tag)!
switch animationType {
case .BottomTop, .BottomBottom, .TopTop, .TopBottom, .LeftLeft, .LeftRight, .RightLeft, .RightRight:
// self.dismissPopupViewController(animationType: animationType)
self.dismissPopupViewController(animationType: animationType)
default:
self.dismissPopupViewController(animationType: SLpopupViewAnimationType.Fade)
}
}
func getTopView() -> UIView {
var recentViewController:UIViewController = self
if let _ = recentViewController.parent {
recentViewController = recentViewController.parent!
}
return recentViewController.view
}
func dismissPopupViewController(animationType: SLpopupViewAnimationType) {
let sourceView:UIView = self.getTopView()
let popupView:UIView = sourceView.viewWithTag(kpopupViewTag)!
let overlayView:UIView = sourceView.viewWithTag(kOverlayViewTag)!
switch animationType {
case .BottomTop, .BottomBottom, .TopTop, .TopBottom, .LeftLeft, .LeftRight, .RightLeft, .RightRight:
self.slideViewOut(popupView: popupView, sourceView: sourceView, overlayView: overlayView, animationType: animationType)
default:
fadeViewOut(popupView: popupView, sourceView: sourceView, overlayView: overlayView)
}
}
}
| mit | bb0b519e4d4095836480003c99c39027 | 45.853448 | 180 | 0.670101 | 4.822538 | false | false | false | false |
BGDigital/mckuai2.0 | mckuai/mckuai/mine/mineHeadViewController.swift | 1 | 7255 | //
// mineHeadViewController.swift
// mckuai
//
// Created by XingfuQiu on 15/4/23.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import UIKit
protocol MineProtocol {
func onRefreshDataSource(iType: Int, iMsgType: Int)
}
class mineHeadViewController: UIViewController, UMSocialUIDelegate {
@IBOutlet weak var imageBg: SABlurImageView!
@IBOutlet weak var roundProgressView: MFRoundProgressView!
@IBOutlet weak var nickname: UILabel!
@IBOutlet weak var locationCity: UIButton!
@IBOutlet weak var btnMsg: UIButton!
@IBOutlet weak var btnDynamic: UIButton!
@IBOutlet weak var btnWork: UIButton!
var Delegate: MineProtocol?
var parentVC: UIViewController!
var lastSelected: UIButton!
var segmentedControl: HMSegmentedControl!
var headImg: String!
var userId = 0
var userLevel = 0
var username = ""
//大类型,小类型都默认取1
var bigType = 1 //1:消息,2:动态,3:作品
var smallType = 1 //0:为空,不用传,1:@Me,2:系统
override func viewDidLoad() {
super.viewDidLoad()
self.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, 325)
initSegmentedControl()
//初始化Button
addSubTextToBtn("消息", parent: btnMsg)
addSubTextToBtn("动态", parent: btnDynamic)
addSubTextToBtn("作品", parent: btnWork)
//设置消息为选中状态
btnMsg.selected = true
lastSelected = btnMsg
if let city = Defaults[D_USER_ADDR].string {
locationCity.setTitle(city, forState: .Normal)
} else {
locationCity.setTitle("未定位", forState: .Normal)
}
}
func addSubTextToBtn(aText: String, parent: UIButton) {
var selectedImg = UIImage.applicationCreateImageWithColor(UIColor(hexString: "#40C84D")!)
parent.setBackgroundImage(selectedImg, forState: .Selected)
parent.setTitleColor(UIColor.whiteColor(), forState: .Selected)
parent.layer.masksToBounds = true
parent.layer.cornerRadius = 25
parent.tintColor = UIColor.clearColor()
parent.titleEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, 0)
var lb = UILabel(frame: CGRectMake(0, btnMsg.bounds.size.height-20, btnMsg.bounds.size.width, 14))
lb.text = aText
lb.font = UIFont(name: lb.font.fontName, size: 12)
lb.textColor = UIColor(hexString: "#FFFFFF") //#BCABA8
lb.highlightedTextColor = UIColor.whiteColor()
lb.textAlignment = .Center
parent.addSubview(lb)
}
func initSegmentedControl() {
segmentedControl = HMSegmentedControl(sectionTitles: ["@你", "系统"])
segmentedControl.frame = CGRectMake(0, self.view.bounds.size.height-35, self.view.bounds.size.width, 35)
segmentedControl.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleWidth
segmentedControl.backgroundColor = UIColor.whiteColor()
segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10)
segmentedControl.textColor = UIColor(red: 0.694, green: 0.694, blue: 0.694, alpha: 1.00)
segmentedControl.selectedTextColor = UIColor(red: 0.255, green: 0.788, blue: 0.298, alpha: 1.00)
segmentedControl.selectionIndicatorHeight = 2
segmentedControl.selectionIndicatorColor = UIColor(red: 0.255, green: 0.788, blue: 0.298, alpha: 1.00)
segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe
segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown
segmentedControl.addTarget(self, action: "segmentSelected:", forControlEvents: UIControlEvents.ValueChanged) //这里不能用ValueChange,会报错!
self.view.addSubview(segmentedControl)
}
@IBAction func segmentSelected(sender: HMSegmentedControl) {
smallType = sender.selectedSegmentIndex
Delegate?.onRefreshDataSource(self.bigType, iMsgType: self.smallType)
}
//这个是大类型
@IBAction func messageSelected(sender: UIButton) {
sender.selected = true
if lastSelected != nil && lastSelected != sender{
lastSelected.selected = false
}
lastSelected = sender
if sender.tag != 1 {
MobClick.event("mineCenter", attributes: ["Type":sender.tag == 2 ? "Dynamic" : "Work"])
segmentedControl.hidden = true
self.smallType = 2
//self.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, 300)
} else {
MobClick.event("mineCenter", attributes: ["Type":"Message"])
segmentedControl.hidden = false
self.smallType = 0
//self.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, 325)
}
bigType = sender.tag
Delegate?.onRefreshDataSource(self.bigType, iMsgType: self.smallType)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//外面调用的函数
func RefreshHead(J: JSON, parent: UIViewController) {
//圆形头像
self.parentVC = parent
roundProgressView.percent = CGFloat(J["process"].floatValue * 100)
self.roundProgressView.imageUrl = J["headImg"].stringValue
self.roundProgressView.level = J["level"].intValue
self.userId = J["id"].intValue
headImg = J["headImg"].stringValue
nickname.text = J["nike"].stringValue
if !headImg.isEmpty {
imageBg.sd_setImageWithURL(NSURL(string: headImg), placeholderImage: UIImage(named: "Avatar"), completed: {image, error, cacheType, imageURL in
// self.roundProgressView.imageView = UIImageView(image: image)
self.imageBg.addBlurEffect(8, times: 1)
})
//
btnMsg.setTitle(J["messageNum"].stringValue, forState: .Normal)
println(btnMsg.titleLabel?.text)
btnDynamic.setTitle(J["dynamicNum"].stringValue, forState: .Normal)
btnWork.setTitle(J["workNum"].stringValue, forState: .Normal)
}
}
func didFinishGetUMSocialDataInViewController(response: UMSocialResponseEntity!) {
if(response.responseCode.value == UMSResponseCodeSuccess.value) {
MobClick.event("Share", attributes: ["Address":"个人中心", "Type": "Success"])
MCUtils.showCustomHUD("分享成功", aType: .Success)
}
}
@IBAction func onShare(sender: AnyObject) {
MobClick.event("mineCenter", attributes: ["Type":"Share"])
var url = "http://www.mckuai.com/u/\(userId)"
println(url)
MobClick.event("Share", attributes: ["Address":"个人中心", "Type": "start"])
ShareUtil.shareInitWithTextAndPicture(parentVC, text: "我的麦块", image: DefaultShareImg!, shareUrl: url, callDelegate: self)
}
@IBAction func setUserInfoAction(sender: UIButton) {
MobClick.event("mineCenter", attributes: ["Type":"Setting"])
UserInfo.showUserInfoView(MCUtils.mainNav,aDelegate: (MCUtils.leftView as! leftMenuViewController))
}
}
| mit | b80217b6b158df52ff5ca12f50c07b45 | 41.125 | 155 | 0.65946 | 4.307365 | false | false | false | false |
scottrhoyt/Jolt | Jolt/Source/FloatingTypeExtensions/FloatingTypeStatisticsExtensions.swift | 1 | 4052 | //
// FloatingTypeStatisticsExtensions.swift
// Jolt
//
// Created by Scott Hoyt on 9/7/15.
// Copyright © 2015 Scott Hoyt. All rights reserved.
//
import Accelerate
extension Double : VectorStatistics {
public static func sum(x: [Double]) -> Double {
var result: Double = 0.0
vDSP_sveD(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func max(x: [Double]) -> Double {
var result: Double = 0.0
vDSP_maxvD(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func min(x: [Double]) -> Double {
var result: Double = 0.0
vDSP_minvD(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func mean(x: [Double]) -> Double {
var result: Double = 0.0
vDSP_meanvD(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func stdev(x: [Double]) -> Double {
var mean: Double = 0
var stdev: Double = 0
vDSP_normalizeD(x, 1, nil, 1, &mean, &stdev, vDSP_Length(x.count))
return stdev
}
public static func normalize(x: [Double]) -> [Double] {
var mean: Double = 0
var stdev: Double = 0
var results = [Double](x)
vDSP_normalizeD(x, 1, &results, 1, &mean, &stdev, vDSP_Length(x.count))
return results
}
public static func variance(x: [Double]) -> Double {
// FIXME: Is there a better way to calculate variance?
return Foundation.pow(stdev(x), 2)
}
public static func covariance(x: [Double], _ y: [Double]) -> Double {
// TODO: Is there a more efficient vector function?
let covariance = mean(Double.mul(Double.sub(x, mean(x)), Double.sub(y, mean(y))))
return covariance
}
public static func correlation(x: [Double], _ y: [Double]) -> Double {
// TODO: Is there a more efficient vector function?
let correlation = covariance(x, y) / (stdev(x) * stdev(y))
return correlation
}
}
extension Float : VectorStatistics {
public static func sum(x: [Float]) -> Float {
var result: Float = 0.0
vDSP_sve(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func max(x: [Float]) -> Float {
var result: Float = 0.0
vDSP_maxv(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func min(x: [Float]) -> Float {
var result: Float = 0.0
vDSP_minv(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func mean(x: [Float]) -> Float {
var result: Float = 0.0
vDSP_meanv(x, 1, &result, vDSP_Length(x.count))
return result
}
public static func stdev(x: [Float]) -> Float {
var mean: Float = 0
var stdev: Float = 0
vDSP_normalize(x, 1, nil, 1, &mean, &stdev, vDSP_Length(x.count))
return stdev
}
public static func normalize(x: [Float]) -> [Float] {
var mean: Float = 0
var stdev: Float = 0
var results = [Float](x)
vDSP_normalize(x, 1, &results, 1, &mean, &stdev, vDSP_Length(x.count))
return results
}
public static func variance(x: [Float]) -> Float {
// FIXME: Is there a better way to calculate variance?
return Foundation.pow(stdev(x), 2)
}
public static func covariance(x: [Float], _ y: [Float]) -> Float {
// TODO: Is there a more efficient vector function?
let covariance = mean(Float.mul(Float.sub(x, mean(x)), Float.sub(y, mean(y))))
return covariance
}
public static func correlation(x: [Float], _ y: [Float]) -> Float {
// TODO: Is there a more efficient vector function?
let correlation = covariance(x, y) / (stdev(x) * stdev(y))
return correlation
}
}
| mit | f1671e64e705d5c40c4df87b409ec56f | 27.528169 | 89 | 0.550728 | 3.754402 | false | false | false | false |
OlliesPage/Feedback-iOS | Feedback/UILoopBarView.swift | 1 | 1874 | //
// UILoopBarView.swift
// Feedback
//
// Created by Oliver Hayman on 09/07/2014.
// Copyright (c) 2014 OlliesPage.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import UIKit
class UILoopBarView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red: 1.0, green: 1.0, blue: (231.0/255.0), alpha: 0)
translatesAutoresizingMaskIntoConstraints = false
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor(red: 1.0, green: 1.0, blue: (231.0/255.0), alpha: 0)
translatesAutoresizingMaskIntoConstraints = false
}
override func drawRect(rect: CGRect) {
// here we're going to draw a line the middle of the way down the rect
let context = UIGraphicsGetCurrentContext()
UIColor.blackColor().setStroke()
CGContextSetLineWidth(context, UIScreen.mainScreen().scale*1.5)
CGContextMoveToPoint(context, 2, 0)
CGContextAddLineToPoint(context, 2, rect.size.height-2)
CGContextAddLineToPoint(context, rect.size.width-2, rect.size.height-2)
CGContextAddLineToPoint(context, rect.size.width-2, 0)
CGContextStrokePath(context)
}
} | gpl-2.0 | 2891216f437ad88a308b2e271aef714a | 37.265306 | 86 | 0.694237 | 4.118681 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Widgets/ToggleButton.swift | 2 | 4575 | // 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 UIKit
private struct UX {
static let BackgroundColor = UIColor.Photon.Purple60
// The amount of pixels the toggle button will expand over the normal size. This results in the larger -> contract animation.
static let ExpandDelta: CGFloat = 5
static let ShowDuration: TimeInterval = 0.4
static let HideDuration: TimeInterval = 0.2
static let BackgroundSize = CGSize(width: 32, height: 32)
}
class ToggleButton: UIButton {
func setSelected(_ selected: Bool, animated: Bool = true) {
self.isSelected = selected
if animated {
animateSelection(selected)
}
}
fileprivate func updateMaskPathForSelectedState(_ selected: Bool) {
let path = CGMutablePath()
if selected {
var rect = CGRect(size: UX.BackgroundSize)
rect.center = maskShapeLayer.position
path.addEllipse(in: rect)
} else {
path.addEllipse(in: CGRect(origin: maskShapeLayer.position, size: .zero))
}
self.maskShapeLayer.path = path
}
fileprivate func animateSelection(_ selected: Bool) {
var endFrame = CGRect(size: UX.BackgroundSize)
endFrame.center = maskShapeLayer.position
if selected {
let animation = CAKeyframeAnimation(keyPath: "path")
let startPath = CGMutablePath()
startPath.addEllipse(in: CGRect(origin: maskShapeLayer.position, size: .zero))
let largerPath = CGMutablePath()
let largerBounds = endFrame.insetBy(dx: -UX.ExpandDelta, dy: -UX.ExpandDelta)
largerPath.addEllipse(in: largerBounds)
let endPath = CGMutablePath()
endPath.addEllipse(in: endFrame)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
animation.values = [
startPath,
largerPath,
endPath
]
animation.duration = UX.ShowDuration
self.maskShapeLayer.path = endPath
self.maskShapeLayer.add(animation, forKey: "grow")
} else {
let animation = CABasicAnimation(keyPath: "path")
animation.duration = UX.HideDuration
animation.fillMode = CAMediaTimingFillMode.forwards
let fromPath = CGMutablePath()
fromPath.addEllipse(in: endFrame)
animation.fromValue = fromPath
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
let toPath = CGMutablePath()
toPath.addEllipse(in: CGRect(origin: self.maskShapeLayer.bounds.center, size: .zero))
self.maskShapeLayer.path = toPath
self.maskShapeLayer.add(animation, forKey: "shrink")
}
}
lazy fileprivate var backgroundView: UIView = {
let view = UIView()
view.isUserInteractionEnabled = false
view.layer.addSublayer(self.backgroundLayer)
return view
}()
lazy fileprivate var maskShapeLayer: CAShapeLayer = {
let circle = CAShapeLayer()
return circle
}()
lazy fileprivate var backgroundLayer: CALayer = {
let backgroundLayer = CALayer()
backgroundLayer.backgroundColor = UX.BackgroundColor.cgColor
backgroundLayer.mask = self.maskShapeLayer
return backgroundLayer
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentMode = .redraw
insertSubview(backgroundView, belowSubview: imageView!)
}
override func layoutSubviews() {
super.layoutSubviews()
let zeroFrame = CGRect(size: frame.size)
backgroundView.frame = zeroFrame
// Make the gradient larger than normal to allow the mask transition to show when it blows up
// a little larger than the resting size
backgroundLayer.bounds = backgroundView.frame.insetBy(dx: -UX.ExpandDelta, dy: -UX.ExpandDelta)
maskShapeLayer.bounds = backgroundView.frame
backgroundLayer.position = CGPoint(x: zeroFrame.midX, y: zeroFrame.midY)
maskShapeLayer.position = CGPoint(x: zeroFrame.midX, y: zeroFrame.midY)
updateMaskPathForSelectedState(isSelected)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 28aa3a8889218865769f2afa855ee9df | 35.6 | 129 | 0.65071 | 5.083333 | false | false | false | false |
ilumanxi/Wind | Wind/Request/URLSessionClient.swift | 1 | 980 | //
// URLSessionClient.swift
// Wind
//
// Created by tanfanfan on 2017/2/7.
// Copyright © 2017年 tanfanfan. All rights reserved.
//
import Foundation
public struct URLSessionClient: Client {
public let host = "https://api.wind.com"
public func send<T: Request>(_ r: T, handler: @escaping (T.Response?) -> Void) {
let url = URL(string: host.appending(r.path))!
var request = URLRequest(url: url)
request.httpMethod = r.method.rawValue
// 在示例中我们不需要 `httpBody`,实践中可能需要将 parameter 转为 data
// request.httpBody = ...
let task = URLSession.shared.dataTask(with: request) {
data, _, error in
if let data = data, let res = T.Response.parse(data: data) {
DispatchQueue.main.async { handler(res) }
} else {
DispatchQueue.main.async { handler(nil) }
}
}
task.resume()
}
}
| mit | 0922fe102aa2564b15b20dabd276233f | 29.225806 | 84 | 0.57524 | 3.793522 | false | false | false | false |
micchyboy1023/Today | Today Watch App/Today Watch Extension/ScoreInterfaceController.swift | 1 | 4959 | //
// ScoreInterfaceController.swift
// TodayWatch Extension
//
// Created by UetaMasamichi on 2016/01/20.
// Copyright © 2016年 Masamichi Ueta. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
import TodayWatchKit
final class ScoreInterfaceController: WKInterfaceController {
@IBOutlet var scoreIcon: WKInterfaceImage!
@IBOutlet var cautionLabel: WKInterfaceLabel!
fileprivate var session: WCSession!
fileprivate var todayScore: Int = 8 {
didSet {
if todayScore == oldValue {
return
}
scoreIcon.setImageNamed(Today.type(todayScore).iconName(.hundred))
}
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if WCSession.isSupported() {
session = WCSession.default()
session.delegate = self
session.activate()
}
}
override func willActivate() {
super.willActivate()
cautionLabel.setHidden(true)
var watchData = WatchData()
if let updatedAt = watchData.updatedAt, Calendar.current.isDate(updatedAt, inSameDayAs: Date()) {
todayScore = watchData.score
}
if session.isReachable {
sendMessageToGetWatchData()
}
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func addToday() {
let watchData = WatchData()
let today = Date()
guard let updatedAt = watchData.updatedAt else {
presentController(withName: "AddTodayInterfaceController", context: self)
return
}
if !Calendar.current.isDate(updatedAt, inSameDayAs: today) {
presentController(withName: "AddTodayInterfaceController", context: self)
} else {
cautionLabel.setHidden(false)
animate(withDuration: 0.5, animations: {
self.cautionLabel.setAlpha(1.0)
Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.hideCautionLabel), userInfo: nil, repeats: false)
})
}
}
func hideCautionLabel() {
animate(withDuration: 0.5, animations: { [unowned self] in
self.cautionLabel.setAlpha(0.0)
self.cautionLabel.setHidden(true)
})
}
fileprivate func sendMessageToGetWatchData() {
session.sendMessage([watchConnectivityActionTypeKey: WatchConnectivityActionType.getWatchData.rawValue],
replyHandler: { content in
var watchData = WatchData()
let score = content[WatchConnectivityContentType.todayScore.rawValue] as? Int
let currentStreak = content[WatchConnectivityContentType.currentStreak.rawValue] as? Int
switch (score, currentStreak) {
case (let .some(score), let .some(currentStreak)):
watchData.score = score
watchData.currentStreak = currentStreak
watchData.updatedAt = Date()
case (let .some(score), nil):
watchData.score = score
watchData.currentStreak = 0
watchData.updatedAt = nil
case (nil, let .some(currentStreak)):
watchData.score = 8
watchData.currentStreak = currentStreak
watchData.updatedAt = nil
case (nil, nil):
watchData.score = 8
watchData.currentStreak = 0
watchData.updatedAt = nil
}
self.todayScore = watchData.score
},
errorHandler: nil)
}
}
//MARK: - WCSessionDelegate
extension ScoreInterfaceController: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
func sessionReachabilityDidChange(_ session: WCSession) {
if session.isReachable {
sendMessageToGetWatchData()
}
}
}
//MARK: - AddTodayInterfaceControllerDelegate
extension ScoreInterfaceController: AddTodayInterfaceControllerDelegate {
func todayDidAdd(_ score: Int) {
todayScore = score
}
}
| mit | da83882c4bcac5f16bb057573a2dee3c | 34.148936 | 144 | 0.530872 | 5.858156 | false | false | false | false |
adrfer/swift | test/attr/attr_fixed_layout.swift | 10 | 1693 | // RUN: %target-swift-frontend -parse -dump-ast -enable-resilience %s 2>&1 | FileCheck --check-prefix=RESILIENCE-ON %s
// RUN: %target-swift-frontend -parse -dump-ast %s 2>&1 | FileCheck --check-prefix=RESILIENCE-OFF %s
//
// Public types with @_fixed_layout are always fixed layout
//
// RESILIENCE-ON: struct_decl "Point" type='Point.Type' access=public @_fixed_layout
// RESILIENCE-OFF: struct_decl "Point" type='Point.Type' access=public @_fixed_layout
@_fixed_layout public struct Point {
let x, y: Int
}
// RESILIENCE-ON: enum_decl "ChooseYourOwnAdventure" type='ChooseYourOwnAdventure.Type' access=public @_fixed_layout
// RESILIENCE-OFF: enum_decl "ChooseYourOwnAdventure" type='ChooseYourOwnAdventure.Type' access=public @_fixed_layout
@_fixed_layout public enum ChooseYourOwnAdventure {
case JumpIntoRabbitHole
case EatMushroom
}
//
// Public types are resilient when -enable-resilience is on
//
// RESILIENCE-ON: struct_decl "Size" type='Size.Type' access=public @_resilient_layout
// RESILIENCE-OFF: struct_decl "Size" type='Size.Type' access=public @_fixed_layout
public struct Size {
let w, h: Int
}
// RESILIENCE-ON: enum_decl "TaxCredit" type='TaxCredit.Type' access=public @_resilient_layout
// RESILIENCE-OFF: enum_decl "TaxCredit" type='TaxCredit.Type' access=public @_fixed_layout
public enum TaxCredit {
case EarnedIncome
case MortgageDeduction
}
//
// Internal types are always fixed layout
//
// RESILIENCE-ON: struct_decl "Rectangle" type='Rectangle.Type' access=internal @_fixed_layout
// RESILIENCE-OFF: struct_decl "Rectangle" type='Rectangle.Type' access=internal @_fixed_layout
struct Rectangle {
let topLeft: Point
let bottomRight: Size
}
| apache-2.0 | 3d2cca016c97c56f69f2c939e482d90e | 35.021277 | 118 | 0.745422 | 3.26834 | false | false | false | false |
Ehrippura/firefox-ios | Shared/SentryIntegration.swift | 1 | 5056 | /* 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 Sentry
public class SentryIntegration {
public static let shared = SentryIntegration()
public static var crashedLastLaunch: Bool {
return Client.shared?.crashedLastLaunch() ?? false
}
private let SentryDSNKey = "SentryDSN"
private let SentryDeviceAppHashKey = "SentryDeviceAppHash"
private let DefaultDeviceAppHash = "0000000000000000000000000000000000000000"
private let DeviceAppHashLength = UInt(20)
private var enabled = false
private var attributes: [String: Any] = [:]
public func setup(sendUsageData: Bool) {
assert(!enabled, "SentryIntegration.setup() should only be called once")
if DeviceInfo.isSimulator() {
Logger.browserLogger.error("Not enabling Sentry; Running in Simulator")
return
}
if !sendUsageData {
Logger.browserLogger.error("Not enabling Sentry; Not enabled by user choice")
return
}
guard let dsn = Bundle.main.object(forInfoDictionaryKey: SentryDSNKey) as? String, !dsn.isEmpty else {
Logger.browserLogger.error("Not enabling Sentry; Not configured in Info.plist")
return
}
Logger.browserLogger.error("Enabling Sentry crash handler")
do {
Client.shared = try Client(dsn: dsn)
try Client.shared?.startCrashHandler()
enabled = true
// If we have not already for this install, generate a completely random identifier
// for this device. It is stored in the app group so that the same value will
// be used for both the main application and the app extensions.
if let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier), defaults.string(forKey: SentryDeviceAppHashKey) == nil {
defaults.set(Bytes.generateRandomBytes(DeviceAppHashLength).hexEncodedString, forKey: SentryDeviceAppHashKey)
defaults.synchronize()
}
// For all outgoing reports, override the default device identifier with our own random
// version. Default to a blank (zero) identifier in case of errors.
Client.shared?.beforeSerializeEvent = { event in
let deviceAppHash = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)?.string(forKey: self.SentryDeviceAppHashKey)
event.context?.appContext?["device_app_hash"] = deviceAppHash ?? self.DefaultDeviceAppHash
var attributes = event.extra ?? [:]
attributes.merge(with: self.attributes)
event.extra = attributes
}
} catch let error {
Logger.browserLogger.error("Failed to initialize Sentry: \(error)")
}
}
public func crash() {
Client.shared?.crash()
}
private func makeEvent(message: String, tag: String, severity: SentrySeverity, extra: [String: Any]?) -> Event {
let event = Event(level: severity)
event.message = message
event.tags = ["tag": tag]
if let extra = extra {
event.extra = extra
}
return event
}
public func send(message: String, tag: String = "general", severity: SentrySeverity = .info, extra: [String: Any]? = nil, completion: SentryRequestFinished? = nil) {
// Do not send messages from SwiftData or BrowserDB unless this is the Beta channel
if !enabled || (AppConstants.BuildChannel != .beta && (tag == "SwiftData" || tag == "BrowserDB" || tag == "NotificationService")) {
if let completion = completion {
completion(nil)
}
return
}
let event = makeEvent(message: message, tag: tag, severity: severity, extra: extra)
Client.shared?.send(event: event, completion: completion)
}
public func sendWithStacktrace(message: String, tag: String = "general", severity: SentrySeverity = .info, extra: [String: Any]? = nil, completion: SentryRequestFinished? = nil) {
// Do not send messages from SwiftData or BrowserDB unless this is the Beta channel
if !enabled || (AppConstants.BuildChannel != .beta && (tag == "SwiftData" || tag == "BrowserDB" || tag == "NotificationService")) {
if let completion = completion {
completion(nil)
}
return
}
Client.shared?.snapshotStacktrace {
let event = self.makeEvent(message: message, tag: tag, severity: severity, extra: extra)
Client.shared?.appendStacktrace(to: event)
event.debugMeta = nil
Client.shared?.send(event: event, completion: completion)
}
}
public func addAttributes(_ attributes: [String: Any]) {
self.attributes.merge(with: attributes)
}
}
| mpl-2.0 | b29389e64b75d619a5c889da287b055a | 41.133333 | 183 | 0.634691 | 5.010902 | false | false | false | false |
coderLL/DYTV | DYTV/DYTV/Classes/Main/Model/AnchorModel.swift | 1 | 828 | //
// AnchorModel.swift
// DYTV
//
// Created by coderLL on 16/10/1.
// Copyright © 2016年 coderLL. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
// 房间ID
var room_id : Int = 0
// 房间图片对应的URLString
var vertical_src : String = ""
// 判断是手机直播还是电脑直播
// 0: 电脑直播(普通房间) 1: 手机直播(秀场房间)
var isVertical : Int = 0
// 房间名称
var room_name : String = ""
// 主播昵称
var nickname : String = ""
// 观看人数
var online : Int = 0
// 主播所在城市
var anchor_city : String = ""
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | 1791c9aefc0a9f2540a2f88c245d769c | 19.371429 | 73 | 0.559607 | 3.529703 | false | false | false | false |
d6u/LarryBird | Source/buildRequest.swift | 1 | 556 | import Foundation
import Alamofire
func buildRequest(config: Config, _ endpoint: Endpoint, _ params: [Param]) -> URLRequestConvertible {
let url = NSURL(string: endpoint.url)!
let mutableUrlRequest = NSMutableURLRequest(URL: url)
mutableUrlRequest.HTTPMethod = endpoint.method
let paramDict = dictionaryFromParams(params)
let authStr = authString(config, endpoint, paramDict)
mutableUrlRequest.setValue(authStr, forHTTPHeaderField: "Authorization")
return UrlEncoder.encode(mutableUrlRequest, parameters: paramDict).0
}
| mit | 489aa349d4eb5d26e5fea1a9fd68123d | 36.066667 | 101 | 0.76259 | 4.834783 | false | true | false | false |
naoyashiga/LegendTV | LegendTV/TopViewController+Settings.swift | 1 | 4799 | //
// TopViewController+Settings.swift
// Gaki
//
// Created by naoyashiga on 2015/08/01.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
extension TopViewController {
func resizedVC() {
if let navVC = childViewControllers.first as? UINavigationController {
if let containerVC = navVC.childViewControllers.first as? ContainerViewController {
let navHeight: CGFloat = 44
let menuHeight: CGFloat = 30
let controlBarHeight: CGFloat = 60
let resizedHeight: CGFloat = view.frame.size.height - playerView.frame.height - controlBarHeight - navHeight - menuHeight
if let homeVC = containerVC.controllerArray[0] as? HomeCollectionViewController {
homeVC.collectionView?.frame.size.height = resizedHeight
}
if let kikakuVC = containerVC.controllerArray[1] as? KikakuCollectionViewController {
kikakuVC.collectionView?.frame.size.height = resizedHeight
}
if let favVC = containerVC.controllerArray[2] as? FavoriteCollectionViewController {
favVC.collectionView?.frame.size.height = resizedHeight
}
if let historyVC = containerVC.controllerArray[3] as? HistoryCollectionViewController {
historyVC.collectionView?.frame.size.height = resizedHeight
}
}
}
}
func applyChildVCDelegate() {
if let navVC = childViewControllers.first as? UINavigationController {
if let containerVC = navVC.childViewControllers.first as? ContainerViewController {
let navHeight: CGFloat = 44
let menuHeight: CGFloat = 30
let resizedHeight: CGFloat = view.frame.size.height - navHeight - menuHeight
if let homeVC = containerVC.controllerArray[0] as? HomeCollectionViewController {
homeVC.delegate = self
homeVC.collectionView?.frame.size.height = resizedHeight
}
if let kikakuVC = containerVC.controllerArray[1] as? KikakuCollectionViewController {
kikakuVC.delegate = self
kikakuVC.collectionView?.frame.size.height = resizedHeight
}
if let favVC = containerVC.controllerArray[2] as? FavoriteCollectionViewController {
favVC.delegate = self
favVC.collectionView?.frame.size.height = resizedHeight
}
if let historyVC = containerVC.controllerArray[3] as? HistoryCollectionViewController {
historyVC.delegate = self
historyVC.collectionView?.frame.size.height = resizedHeight
}
let videoCollectionVC = VideoCollectionViewController()
videoCollectionVC.delegate = self
}
}
}
func addFoldVideoControlButton() {
navigationItem.leftBarButtonItem = nil
navigationItem.hidesBackButton = true
let foldVideoControlButton = UIButton(type: UIButtonType.Custom)
foldVideoControlButton.frame = CGRectMake(0, 0, 40, 40)
foldVideoControlButton.setImage(UIImage(named:ButtonSet.foldVideo), forState: UIControlState.Normal)
foldVideoControlButton.setImage(UIImage(named:ButtonSet.unfoldVideo), forState: UIControlState.Selected)
foldVideoControlButton.tintColor = UIColor.whiteColor()
foldVideoControlButton.selected = false
foldVideoControlButton.addTarget(self, action: "foldVideoControlButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
let leftBarButtonItem = UIBarButtonItem(customView: foldVideoControlButton)
navigationItem.setLeftBarButtonItem(leftBarButtonItem, animated: false)
}
func addShareButton() {
navigationItem.rightBarButtonItem = nil
let shareButton = UIButton(type: UIButtonType.Custom)
shareButton.frame = CGRectMake(0, 0, 40, 40)
shareButton.setImage(UIImage(named:ButtonSet.share), forState: UIControlState.Normal)
shareButton.tintColor = UIColor.whiteColor()
shareButton.addTarget(self, action: "shareButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
let rightBarButtonItem = UIBarButtonItem(customView: shareButton)
navigationItem.setRightBarButtonItem(rightBarButtonItem, animated: true)
}
} | mit | 49cd5b6172d95e2eaa632948ef430945 | 44.264151 | 137 | 0.622472 | 5.966418 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/FeaturedApps/ECGChartView.swift | 1 | 3735 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// ECGChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
enum TraceAOrB {
case TraceA
case TraceB
}
class ECGChartView: SingleChartLayout {
let TimeInterval = 0.02;
var _series0: SCIXyDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
var _series1: SCIXyDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
let _sourceData = DataManager.loadWaveformData()
var _timer: Timer!
var _currentIndex: Int = 0
var _totalIndex = 0.0
var _whichTrace: TraceAOrB = .TraceA
override func initExample() {
let xAxis = SCINumericAxis()
xAxis.autoRange = .never
xAxis.axisTitle = "Time (seconds)"
xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(0), max: SCIGeneric(10))
let yAxis = SCINumericAxis()
yAxis.autoRange = .never
yAxis.axisTitle = "Voltage (mV)"
yAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(-0.5), max: SCIGeneric(1.5))
_series0.fifoCapacity = 3850
_series1.fifoCapacity = 3850
let rSeries0 = SCIFastLineRenderableSeries()
rSeries0.dataSeries = _series0;
let rSeries1 = SCIFastLineRenderableSeries()
rSeries1.dataSeries = _series1;
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
self.surface.renderableSeries.add(rSeries0)
self.surface.renderableSeries.add(rSeries1)
SCIThemeManager.applyDefaultTheme(toThemeable: self.surface)
}
}
@objc fileprivate func appendData() {
for _ in 0..<10 {
appendPoint(400)
}
}
fileprivate func appendPoint(_ sampleRate: Double) {
if _currentIndex >= _sourceData!.count {
_currentIndex = 0
}
// Get the next voltage and time, and append to the chart
let voltage = Double(_sourceData![_currentIndex] as! String)!
let time = fmod(_totalIndex / sampleRate, 10.0)
if (_whichTrace == .TraceA) {
_series0.appendX(SCIGeneric(time), y: SCIGeneric(voltage))
_series1.appendX(SCIGeneric(time), y: SCIGeneric(Double.nan))
} else {
_series0.appendX(SCIGeneric(time), y: SCIGeneric(Double.nan))
_series1.appendX(SCIGeneric(time), y: SCIGeneric(voltage))
}
_currentIndex += 1
_totalIndex += 1
if (Int(_totalIndex) % 4000 == 0) {
_whichTrace = _whichTrace == .TraceA ? .TraceB : .TraceA;
}
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if _timer == nil {
_timer = Timer.scheduledTimer(timeInterval: TimeInterval, target: self, selector: #selector(appendData), userInfo: nil, repeats: true)
} else {
_timer.invalidate()
_timer = nil
}
}
}
| mit | 5bf1f4eef9aba48ccdda6373a2397bd5 | 34.542857 | 146 | 0.594587 | 4.370023 | false | false | false | false |
tingkerians/master | doharmony/ProfileViewController.swift | 1 | 1951 | //
// ViewController.swift
// PageMenuDemoStoryboard
//
// Created by Niklas Fahl on 12/19/14.
// Copyright (c) 2014 CAPS. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewControllerProtectedPage,UITabBarControllerDelegate {
var pageMenu : CAPSPageMenu?
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
// Initialize view controllers to display and place in array
var controllerArray : [UIViewController] = []
let controller1 : MyProfileViewController = MyProfileViewController(nibName: "MyProfileViewController", bundle: nil)
controller1.title = locale.Profile
controllerArray.append(controller1)
let controller2 : LibrariesTableViewController = LibrariesTableViewController(nibName: "LibrariesTableViewController", bundle: nil)
controller2.title = locale.Track
controllerArray.append(controller2)
let controller3 : LibrariesTableViewController = LibrariesTableViewController(nibName: "LibrariesTableViewController", bundle: nil)
controller3.title = locale.Project
controllerArray.append(controller3)
// Initialize scroll menu
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: env.CAPSPageMenuOptions)
self.addChildViewController(pageMenu!)
self.view.addSubview(pageMenu!.view)
}
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
let selectedIndex = tabBarController.viewControllers?.indexOf(viewController)
tabBarTransition.selectedIndex = selectedIndex
tabBarTransition.prevSelectedIndex = tabBarController.selectedIndex
return true
}
}
| unlicense | 555016c657f7f2d895edfbb8be451d22 | 38.02 | 183 | 0.719118 | 5.638728 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIComponents/QMUIButton/QMUINavigationButton.swift | 1 | 23975 | //
// QMUINavigationButton.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/5/3.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
enum QMUINavigationButtonType {
case normal // 普通导航栏文字按钮
case bold // 导航栏加粗按钮
case image // 图标按钮
case back // 自定义返回按钮(可以同时带有title)
case close // 自定义关闭按钮(只显示icon不带title)
}
enum QMUINavigationButtonPosition: Int {
case none = -1 // 不处于navigationBar最左(右)边的按钮,则使用None。用None则不会在alignmentRectInsets里调整位置
case left // 用于leftBarButtonItem,如果用于leftBarButtonItems,则只对最左边的item使用,其他item使用QMUINavigationButtonPositionNone
case right // 用于rightBarButtonItem,如果用于rightBarButtonItems,则只对最右边的item使用,其他item使用QMUINavigationButtonPositionNone
}
/**
* QMUINavigationButton 有两部分组成:
* 一部分是 UIBarButtonItem (QMUINavigationButton),提供比系统更便捷的类方法来快速初始化一个 UIBarButtonItem,推荐首选这种方式(原则是能用系统的尽量用系统的,不满足才用自定义的)。
* 另一部分就是 QMUINavigationButton,会提供一个按钮,作为 customView 给 UIBarButtonItem 使用,这种常用于自定义的返回按钮。
* 对于第二种按钮,会尽量保证样式、布局看起来都和系统的 UIBarButtonItem 一致,所以内部做了许多 iOS 版本兼容的微调。
*/
class QMUINavigationButton: UIButton {
/**
* 获取当前按钮的`QMUINavigationButtonType`
*/
private(set) var type: QMUINavigationButtonType = .normal
fileprivate var buttonPosition: QMUINavigationButtonPosition = .none
private var defaultHighlightedImage: UIImage? // 在 set normal image 时自动拿 normal image 加 alpha 作为 highlighted image
private var defaultDisabledImage: UIImage? // 在 set normal image 时自动拿 normal image 加 alpha 作为 disabled image
convenience init() {
self.init(type: .normal)
}
/**
* 导航栏按钮的初始化函数,指定的初始化方法
* @param type 按钮类型
* @param title 按钮的title
*/
init(type: QMUINavigationButtonType, title: String?) {
super.init(frame: .zero)
self.type = type
setTitle(title, for: .normal)
renderButtonStyle()
sizeToFit()
}
/**
* 导航栏按钮的初始化函数
* @param type 按钮类型
*/
convenience init(type: QMUINavigationButtonType) {
self.init(type: type, title: nil)
}
/**
* 导航栏按钮的初始化函数
* @param image 按钮的image
*/
convenience init(image: UIImage) {
self.init(type: .image)
setImage(image, for: .normal)
// 系统在iOS8及以后的版本默认对image的UIBarButtonItem加了上下3、左右11的padding,所以这里统一一下
contentEdgeInsets = UIEdgeInsets.init(top: 3, left: 11, bottom: 3, right: 11)
sizeToFit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// 修复系统的UIBarButtonItem里的图片无法跟着tintColor走
override func setImage(_ image: UIImage?, for state: UIControl.State) {
if var image = image, self.image(for: state) != image {
if image.renderingMode == .automatic {
// 由于 QMUINavigationButton 是用于 UIBarButtonItem 的,所以默认的行为应该是尽量去跟随 tintColor,所以做了这个优化
image = image.withRenderingMode(.alwaysTemplate)
}
if state == .normal {
// 将 normal image 处理成对应的 highlighted image 和 disabled image
defaultHighlightedImage = image.qmui_image(alpha: NavBarHighlightedAlpha)?.withRenderingMode(image.renderingMode)
setImage(defaultHighlightedImage, for: .highlighted)
defaultDisabledImage = image.qmui_image(alpha: NavBarDisabledAlpha)?.withRenderingMode(image.renderingMode)
setImage(defaultDisabledImage, for: .disabled)
} else {
// 如果业务主动设置了非 normal 状态的 image,则把之前 QMUI 自动加上的两个 image 去掉,相当于认为业务希望完全控制这个按钮在所有 state 下的图片
if image != defaultHighlightedImage && image != defaultDisabledImage {
if self.image(for: .highlighted) == defaultHighlightedImage && state != .highlighted {
setImage(nil, for: .highlighted)
}
if self.image(for: .disabled) == defaultDisabledImage && state != .disabled {
setImage(nil, for: .disabled)
}
}
}
super.setImage(image, for: state)
} else {
super.setImage(image, for: state)
}
}
// 自定义nav按钮,需要根据这个来修改title的三态颜色
override func tintColorDidChange() {
super.tintColorDidChange()
setTitleColor(tintColor, for: .normal)
setTitleColor(tintColor.withAlphaComponent(NavBarHighlightedAlpha), for: .highlighted)
setTitleColor(tintColor.withAlphaComponent(NavBarDisabledAlpha), for: .disabled)
}
// 对按钮内容添加偏移,让UIBarButtonItem适配最新设备的系统行为,统一位置
override var alignmentRectInsets: UIEdgeInsets {
var insets = super.alignmentRectInsets
if type == .normal || type == .bold {
// 文字类型的按钮,分别对最左、最右那个按钮调整 inset(这里与 UINavigationItem(QMUINavigationButton) 里的 position 赋值配合使用)
if #available(iOS 10, *) {
} else {
if buttonPosition == .left {
insets.left = 8
} else if buttonPosition == .right {
insets.right = 8
}
}
// 对于奇数大小的字号,不同 iOS 版本的偏移策略不同,统一一下
if let titleLabel = titleLabel, titleLabel.font.pointSize / 2.0 > 0 {
if #available(iOS 11, *) {
insets.top = PixelOne
insets.bottom = -PixelOne
} else {
insets.top = -PixelOne
insets.bottom = PixelOne
}
}
} else if type == .image {
// 图片类型的按钮,分别对最左、最右那个按钮调整 inset(这里与 UINavigationItem(QMUINavigationButton) 里的 position 赋值配合使用)
if buttonPosition == .left {
insets.left = 11
} else if buttonPosition == .right {
insets.right = 11
}
insets.top = 1
} else if type == .back {
insets.top = PixelOne
if #available(iOS 11, *) {
} else {
insets.left = 8
}
}
return insets
}
private func renderButtonStyle() {
if let font = NavBarButtonFont {
titleLabel?.font = font
}
titleLabel?.backgroundColor = UIColorClear
titleLabel?.lineBreakMode = .byTruncatingTail
contentMode = .center
contentHorizontalAlignment = .center
contentVerticalAlignment = .center
qmui_automaticallyAdjustTouchHighlightedInScrollView = true
// 系统默认对 highlighted 和 disabled 的图片的表现是变身色,但 UIBarButtonItem 是 alpha,为了与 UIBarButtonItem 表现一致,这里禁用了 UIButton 默认的行为,然后通过重写 setImage:forState:,自动将 normal image 处理为对应的 highlighted image 和 disabled image
adjustsImageWhenHighlighted = false
adjustsImageWhenDisabled = false
if #available(iOS 11, *) {
translatesAutoresizingMaskIntoConstraints = false// 打开这个才能让 iOS 11 下的 alignmentRectInsets 生效
}
switch type {
case .image:
// 拓展宽度,以保证用 leftBarButtonItems/rightBarButtonItems 时,按钮与按钮之间间距与系统的保持一致
contentEdgeInsets = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 11)
case .bold:
if let font = NavBarButtonFontBold{
titleLabel?.font = font
}
case .back:
// 配置表没有自定义的图片,则按照系统的返回按钮图片样式创建一张
let backIndicatorImage = NavBarBackIndicatorImage ?? UIImage.qmui_image(shape: .navBack, size: CGSize(width: 13, height: 23), lineWidth: 3, tintColor: NavBarTintColor)!
setImage(backIndicatorImage, for: .normal)
setImage(backIndicatorImage.qmui_image(alpha: NavBarHighlightedAlpha), for: .highlighted)
setImage(backIndicatorImage.qmui_image(alpha: NavBarDisabledAlpha), for: .disabled)
contentHorizontalAlignment = .center
// @warning 这些数值都是每个iOS版本核对过没问题的,如果修改则要检查要每个版本里与系统UIBarButtonItem的布局是否一致
let titleOffsetBaseOnSystem = UIOffset(horizontal: IOS_VERSION >= 11.0 ? 6 : 7, vertical: 0) // 经过这些数值的调整后,自定义返回按钮的位置才能和系统默认返回按钮的位置对准,而配置表里设置的值是在这个调整的基础上再调整
let configurationOffset = NavBarBarBackButtonTitlePositionAdjustment
titleEdgeInsets = UIEdgeInsets(top: titleOffsetBaseOnSystem.vertical + configurationOffset.vertical, left: titleOffsetBaseOnSystem.horizontal + configurationOffset.horizontal, bottom: -titleOffsetBaseOnSystem.vertical - configurationOffset.vertical, right: -titleOffsetBaseOnSystem.horizontal - configurationOffset.horizontal)
contentEdgeInsets = UIEdgeInsets(top: IOS_VERSION < 11.0 ? 1 : 0, left: 0, bottom: 0, right: titleEdgeInsets.left) // iOS 11 以前,y 值偏移一点
default:
break
}
}
}
extension UIBarButtonItem {
static func item(button: QMUINavigationButton,
target: Any?,
action: Selector?) -> UIBarButtonItem {
if let action = action {
button.addTarget(target, action: action, for: .touchUpInside)
}
return UIBarButtonItem(customView: button)
}
static func item(image: UIImage?,
target: Any?,
action: Selector?) -> UIBarButtonItem {
return UIBarButtonItem(image: image, style: .plain, target: target, action: action)
}
static func item(title: String?,
target: Any?,
action: Selector?) -> UIBarButtonItem {
return UIBarButtonItem(title: title, style: .plain, target: target, action: action)
}
static func item(boldTitle: String?,
target: Any?,
action: Selector?) -> UIBarButtonItem {
return UIBarButtonItem(title: boldTitle, style: .done, target: target, action: action)
}
static func backItem(target: Any?,
action: Selector?) -> UIBarButtonItem {
var backTitle: String
if NeedsBackBarButtonItemTitle {
backTitle = "返回"; // 默认文字用返回
if let viewController = target as? UIViewController {
let previousViewController = viewController.qmui_previousViewController
if let item = previousViewController?.navigationItem.backBarButtonItem {
// 如果前一个界面有主动设置返回按钮的文字,则取这个文字
backTitle = item.title ?? ""
} else if let viewController = viewController as? QMUINavigationControllerAppearanceDelegate {
// 否则看是否有通过 QMUI 提供的接口来设置返回按钮的文字,有就用它的值
backTitle = viewController.backBarButtonItemTitle?(previousViewController) ?? ""
} else if let title = previousViewController?.title {
// 否则取上一个界面的标题
backTitle = title
}
}
} else {
backTitle = " "
}
let button = QMUINavigationButton(type: .back, title: backTitle)
if let action = action {
button.addTarget(target, action: action, for: .touchUpInside)
}
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
static func closeItem(target: Any?,
action: Selector?) -> UIBarButtonItem {
let barButtonItem = UIBarButtonItem(image: NavBarCloseButtonImage, style: .plain, target: target, action: action)
return barButtonItem
}
static func fixedSpaceItem(width: CGFloat) -> UIBarButtonItem {
let item = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
item.width = width
return item
}
static func flexibleSpaceItem() -> UIBarButtonItem {
let item = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
return item
}
}
extension UIBarButtonItem {
/// 判断当前的 UIBarButtonItem 是否是 QMUINavigationButton
fileprivate var qmui_isCustomizedBarButtonItem: Bool {
guard let _ = customView as? QMUINavigationButton else {
return false
}
return true
}
/// 判断当前的 UIBarButtonItem 是否是用 QMUINavigationButton 自定义返回按钮生成的
fileprivate var qmui_isCustomizedBackBarButtonItem: Bool {
guard let customView = customView as? QMUINavigationButton else {
return false
}
let result = qmui_isCustomizedBarButtonItem && customView.type == .back
return result
}
/// 获取内部的 QMUINavigationButton(如果有的话)
fileprivate var qmui_navigationButton: QMUINavigationButton? {
guard let customView = customView as? QMUINavigationButton else {
return nil
}
return customView
}
}
extension UINavigationItem: SelfAware2 {
private static let _onceToken = UUID().uuidString
static func awake2() {
DispatchQueue.once(token: _onceToken) {
let clazz = UINavigationItem.self
ReplaceMethod(clazz, #selector(UINavigationItem.setLeftBarButton(_:animated:)), #selector(UINavigationItem.qmui_setLeftBarButton(_:animated:)))
ReplaceMethod(clazz, #selector(UINavigationItem.setLeftBarButtonItems(_:animated:)), #selector(UINavigationItem.qmui_setLeftBarButtonItems(_:animated:)))
ReplaceMethod(clazz, #selector(UINavigationItem.setRightBarButton(_:animated:)), #selector(UINavigationItem.qmui_setRightBarButton(_:animated:)))
ReplaceMethod(clazz, #selector(UINavigationItem.setRightBarButtonItems(_:animated:)), #selector(UINavigationItem.qmui_setRightBarButtonItems(_:animated:)))
}
}
@objc func qmui_setLeftBarButton(_ item: UIBarButtonItem, animated: Bool) {
if detectSetItemsWhenPopping {
tempLeftBarButtonItems = [item]
return
}
qmui_setLeftBarButton(item, animated: animated)
// 自动给 position 赋值
item.qmui_navigationButton?.buttonPosition = .left
// iOS 11,调整自定义返回按钮的位置 https://github.com/QMUI/QMUI_iOS/issues/279
if #available(iOS 11, *) {
guard let navigationBar = qmui_navigationBar else {
return
}
navigationBar.qmui_customizingBackBarButtonItem = item.qmui_isCustomizedBackBarButtonItem
}
}
@objc func qmui_setLeftBarButtonItems(_ items: [UIBarButtonItem], animated: Bool) {
if detectSetItemsWhenPopping {
tempLeftBarButtonItems = items
return
}
qmui_setLeftBarButtonItems(items, animated: animated)
// 自动给 position 赋值
for (i, item) in items.enumerated() {
if i == 0 {
item.qmui_navigationButton?.buttonPosition = .left
} else {
item.qmui_navigationButton?.buttonPosition = .none
}
}
// iOS 11,调整自定义返回按钮的位置 https://github.com/QMUI/QMUI_iOS/issues/279
if #available(iOS 11, *) {
guard let navigationBar = qmui_navigationBar else {
return
}
var customizingBackBarButtonItem = false
for item in items {
if item.qmui_isCustomizedBackBarButtonItem {
customizingBackBarButtonItem = true
break
}
}
navigationBar.qmui_customizingBackBarButtonItem = customizingBackBarButtonItem
}
}
@objc func qmui_setRightBarButton(_ item: UIBarButtonItem, animated: Bool) {
if detectSetItemsWhenPopping {
tempRightBarButtonItems = [item]
return
}
qmui_setRightBarButton(item, animated: animated)
// 自动给 position 赋值
item.qmui_navigationButton?.buttonPosition = .right
}
@objc func qmui_setRightBarButtonItems(_ items: [UIBarButtonItem], animated: Bool) {
if detectSetItemsWhenPopping {
tempRightBarButtonItems = items
return
}
qmui_setRightBarButtonItems(items, animated: animated)
// 自动给 position 赋值
for (i, item) in items.enumerated() {
if i == 0 {
item.qmui_navigationButton?.buttonPosition = .right
} else {
item.qmui_navigationButton?.buttonPosition = .none
}
}
}
private struct Keys {
static var tempLeftBarButtonItems = "tempLeftBarButtonItems"
static var tempRightBarButtonItems = "tempRightBarButtonItems"
}
fileprivate var tempLeftBarButtonItems: [UIBarButtonItem]? {
set {
objc_setAssociatedObject(self, &Keys.tempLeftBarButtonItems, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &Keys.tempLeftBarButtonItems) as? [UIBarButtonItem]
}
}
fileprivate var tempRightBarButtonItems: [UIBarButtonItem]? {
set {
objc_setAssociatedObject(self, &Keys.tempRightBarButtonItems, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &Keys.tempRightBarButtonItems) as? [UIBarButtonItem]
}
}
// 监控是否在 iOS 10 及以下,手势返回的过程中,手势返回背后的那个界面修改了 navigationItem,这可能导致 bug:https://github.com/QMUI/QMUI_iOS/issues/302
private var detectSetItemsWhenPopping: Bool {
if #available(iOS 11, *) {
} else {
if let qmui_navigationBar = qmui_navigationBar, let navController = qmui_navigationBar.delegate as? UINavigationController {
if navController.topViewController?.qmui_willAppearByInteractivePopGestureRecognizer ?? false && navController.topViewController?.qmui_navigationControllerPopGestureRecognizerChanging ?? false {
// 注意,判断条件里的 qmui_navigationControllerPopGestureRecognizerChanging 关键在于,它是在 viewWillAppear: 执行后才被置为 YES,而 QMUICommonViewController 是在 viewWillAppear: 里调用 setNavigationItems:,所以刚好过滤了这种场景。因为测试过,在 viewWillAppear: 里操作 items 是没问题的,但在那之后的操作就会有问题。
print("UINavigationItem (QMUINavigationButton) 拦截了一次可能产生顶部按钮混乱的操作,navigationController is \(navController), topViewController is \(String(describing: navController.topViewController))")
return true
}
}
}
return false
}
fileprivate weak var qmui_navigationBar: UINavigationBar? {
// UINavigationItem 内部有个方法可以获取 navigationBar
guard self.responds(to: #selector(getter: UINavigationController.navigationBar)) else {
return nil
}
let result = perform(#selector(getter: UINavigationController.navigationBar)).takeRetainedValue() as? UINavigationBar
return result
}
}
extension UIViewController {
@objc func navigationButton_viewDidAppear(_ animated: Bool) {
navigationButton_viewDidAppear(animated)
if let tempLeftBarButtonItems = navigationItem.tempLeftBarButtonItems {
print("UIViewController (QMUINavigationButton) \(String(describing: type(of: self))) 在 viewDidAppear: 重新设置了 leftBarButtonItems: \(String(describing: navigationItem.tempLeftBarButtonItems))")
navigationItem.leftBarButtonItems = tempLeftBarButtonItems
navigationItem.tempLeftBarButtonItems = nil
}
if let tempRightBarButtonItems = navigationItem.tempRightBarButtonItems {
print("UIViewController (QMUINavigationButton) \(String(describing: type(of: self))) 在 viewDidAppear: 重新设置了 rightBarButtonItems: \(String(describing: navigationItem.tempRightBarButtonItems))")
navigationItem.rightBarButtonItems = tempRightBarButtonItems
navigationItem.tempRightBarButtonItems = nil
}
}
}
extension UINavigationBar {
/// 获取 navigationBar 内部的 contentView
fileprivate weak var qmui_contentView: UIView? {
for subview in subviews {
if String(describing: type(of: subview)).contains("ContentView") {
return subview
}
}
return nil
}
private struct Keys {
static var customizingBackBarButtonItem = "customizingBackBarButtonItem"
}
/// 判断当前的 UINavigationBar 的返回按钮是不是自定义的
fileprivate var qmui_customizingBackBarButtonItem: Bool {
set {
objc_setAssociatedObject(self, &Keys.customizingBackBarButtonItem, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if #available(iOS 11, *) {
if let contentView = qmui_contentView, contentView.safeAreaInsets.left == 0, contentView.safeAreaInsets.right == 0 {
// TODO: molice iPhone X 横屏下,这段代码会导致 margins 不断变大,待解决,目前先屏蔽横屏的情况(也即 safeAreaInsets 左右不为0)
var layoutMargins = contentView.directionalLayoutMargins
let leadingMargin = max(0, layoutMargins.trailing - contentView.safeAreaInsets.right - (qmui_customizingBackBarButtonItem ? 8 : 0))
if layoutMargins.leading != leadingMargin {
layoutMargins.leading = leadingMargin
contentView.directionalLayoutMargins = layoutMargins
}
}
}
}
get {
return objc_getAssociatedObject(self, &Keys.customizingBackBarButtonItem) as? Bool ?? false
}
}
}
| mit | a9bfb1913204391a3e06629bb90c0758 | 40.116635 | 338 | 0.627186 | 4.896175 | false | false | false | false |
atrick/swift | stdlib/public/core/StringUTF8View.swift | 1 | 19893 | //===--- StringUTF8.swift - A UTF8 view of String -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-8 code units.
///
/// You can access a string's view of UTF-8 code units by using its `utf8`
/// property. A string's UTF-8 view encodes the string's Unicode scalar
/// values as 8-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf8 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 240
/// // 159
/// // 146
/// // 144
///
/// A string's Unicode scalar values can be up to 21 bits in length. To
/// represent those scalar values using 8-bit integers, more than one UTF-8
/// code unit is often required.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf8 {
/// print(v)
/// }
/// // 240
/// // 159
/// // 146
/// // 144
///
/// In the encoded representation of a Unicode scalar value, each UTF-8 code
/// unit after the first is called a *continuation byte*.
///
/// UTF8View Elements Match Encoded C Strings
/// =========================================
///
/// Swift streamlines interoperation with C string APIs by letting you pass a
/// `String` instance to a function as an `Int8` or `UInt8` pointer. When you
/// call a C function using a `String`, Swift automatically creates a buffer
/// of UTF-8 code units and passes a pointer to that buffer. The code units
/// of that buffer match the code units in the string's `utf8` view.
///
/// The following example uses the C `strncmp` function to compare the
/// beginning of two Swift strings. The `strncmp` function takes two
/// `const char*` pointers and an integer specifying the number of characters
/// to compare. Because the strings are identical up to the 14th character,
/// comparing only those characters results in a return value of `0`.
///
/// let s1 = "They call me 'Bell'"
/// let s2 = "They call me 'Stacey'"
///
/// print(strncmp(s1, s2, 14))
/// // Prints "0"
/// print(String(s1.utf8.prefix(14))!)
/// // Prints "They call me '"
///
/// Extending the compared character count to 15 includes the differing
/// characters, so a nonzero result is returned.
///
/// print(strncmp(s1, s2, 15))
/// // Prints "-17"
/// print(String(s1.utf8.prefix(15))!)
/// // Prints "They call me 'B"
@frozen
public struct UTF8View: Sendable {
@usableFromInline
internal var _guts: _StringGuts
@inlinable @inline(__always)
internal init(_ guts: _StringGuts) {
self._guts = guts
_invariantCheck()
}
}
}
extension String.UTF8View {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
// TODO: Ensure index alignment
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UTF8View: BidirectionalCollection {
public typealias Index = String.Index
public typealias Element = UTF8.CodeUnit
/// The position of the first code unit if the UTF-8 view is
/// nonempty.
///
/// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`.
@inlinable @inline(__always)
public var startIndex: Index { return _guts.startIndex }
/// The "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In an empty UTF-8 view, `endIndex` is equal to `startIndex`.
@inlinable @inline(__always)
public var endIndex: Index { return _guts.endIndex }
/// Returns the next consecutive position after `i`.
///
/// - Precondition: The next position is representable.
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
let i = _guts.ensureMatchingEncoding(i)
if _fastPath(_guts.isFastUTF8) {
// Note: deferred bounds check
return i.strippingTranscoding.nextEncoded._knownUTF8
}
_precondition(i._encodedOffset < _guts.count,
"String index is out of bounds")
return _foreignIndex(after: i)
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
let i = _guts.ensureMatchingEncoding(i)
_precondition(!i.isZeroPosition, "String index is out of bounds")
if _fastPath(_guts.isFastUTF8) {
return i.strippingTranscoding.priorEncoded._knownUTF8
}
_precondition(i._encodedOffset <= _guts.count,
"String index is out of bounds")
return _foreignIndex(before: i)
}
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let i = _guts.ensureMatchingEncoding(i)
if _fastPath(_guts.isFastUTF8) {
let offset = n + i._encodedOffset
_precondition(offset >= 0 && offset <= _guts.count,
"String index is out of bounds")
return Index(_encodedOffset: offset)._knownUTF8
}
return _foreignIndex(i, offsetBy: n)
}
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
let i = _guts.ensureMatchingEncoding(i)
if _fastPath(_guts.isFastUTF8) {
// Check the limit: ignore limit if it precedes `i` (in the correct
// direction), otherwise must not be beyond limit (in the correct
// direction).
let iOffset = i._encodedOffset
let result = iOffset + n
let limitOffset = limit._encodedOffset
if n >= 0 {
guard limitOffset < iOffset || result <= limitOffset else { return nil }
} else {
guard limitOffset > iOffset || result >= limitOffset else { return nil }
}
_precondition(result >= 0 && result <= _guts.count,
"String index is out of bounds")
return Index(_encodedOffset: result)
}
return _foreignIndex(i, offsetBy: n, limitedBy: limit)
}
@inlinable @inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
let i = _guts.ensureMatchingEncoding(i)
let j = _guts.ensureMatchingEncoding(j)
if _fastPath(_guts.isFastUTF8) {
return j._encodedOffset &- i._encodedOffset
}
_precondition(
i._encodedOffset <= _guts.count && j._encodedOffset <= _guts.count,
"String index is out of bounds")
return _foreignDistance(from: i, to: j)
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-8 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf8.startIndex
/// print("First character's UTF-8 code unit: \(greeting.utf8[i])")
/// // Prints "First character's UTF-8 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position`
/// must be less than the view's end index.
@inlinable @inline(__always)
public subscript(i: Index) -> UTF8.CodeUnit {
let i = _guts.ensureMatchingEncoding(i)
_precondition(i._encodedOffset < _guts.count,
"String index is out of bounds")
return self[_unchecked: i]
}
@_alwaysEmitIntoClient @inline(__always)
internal subscript(_unchecked i: Index) -> UTF8.CodeUnit {
if _fastPath(_guts.isFastUTF8) {
return _guts.withFastUTF8 { utf8 in utf8[_unchecked: i._encodedOffset] }
}
return _foreignSubscript(position: i)
}
}
extension String.UTF8View: CustomStringConvertible {
@inlinable @inline(__always)
public var description: String { return String(_guts) }
}
extension String.UTF8View: CustomDebugStringConvertible {
public var debugDescription: String {
return "UTF8View(\(self.description.debugDescription))"
}
}
extension String {
/// A UTF-8 encoding of `self`.
@inlinable
public var utf8: UTF8View {
@inline(__always) get { return UTF8View(self._guts) }
set { self = String(newValue._guts) }
}
/// A contiguously stored null-terminated UTF-8 representation of the string.
///
/// To access the underlying memory, invoke `withUnsafeBufferPointer` on the
/// array.
///
/// let s = "Hello!"
/// let bytes = s.utf8CString
/// print(bytes)
/// // Prints "[72, 101, 108, 108, 111, 33, 0]"
///
/// bytes.withUnsafeBufferPointer { ptr in
/// print(strlen(ptr.baseAddress!))
/// }
/// // Prints "6"
public var utf8CString: ContiguousArray<CChar> {
@_effects(readonly) @_semantics("string.getUTF8CString")
get {
if _fastPath(_guts.isFastUTF8) {
var result = _guts.withFastCChar { ContiguousArray($0) }
result.append(0)
return result
}
return _slowUTF8CString()
}
}
@usableFromInline @inline(never) // slow-path
internal func _slowUTF8CString() -> ContiguousArray<CChar> {
var result = ContiguousArray<CChar>()
result.reserveCapacity(self._guts.count + 1)
for c in self.utf8 {
result.append(CChar(bitPattern: c))
}
result.append(0)
return result
}
/// Creates a string corresponding to the given sequence of UTF-8 code units.
@available(swift, introduced: 4.0, message:
"Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode")
@inlinable @inline(__always)
public init(_ utf8: UTF8View) {
self = String(utf8._guts)
}
}
extension String.UTF8View {
@inlinable @inline(__always)
public var count: Int {
if _fastPath(_guts.isFastUTF8) {
return _guts.count
}
return _foreignCount()
}
}
// Index conversions
extension String.UTF8View.Index {
/// Creates an index in the given UTF-8 view that corresponds exactly to the
/// specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `utf8` view.
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.firstIndex(of: 32)!
/// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)!
///
/// print(Array(cafe.utf8[..<utf8Index]))
/// // Prints "[67, 97, 102, 195, 169]"
///
/// If the position passed in `utf16Index` doesn't have an exact
/// corresponding position in `utf8`, the result of the initializer is
/// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code
/// points differently, an attempt to convert the position of the trailing
/// surrogate of a UTF-16 surrogate pair fails.
///
/// The next example attempts to convert the indices of the two UTF-16 code
/// points that represent the teacup emoji (`"🍵"`). The index of the lead
/// surrogate is successfully converted to a position in `utf8`, but the
/// index of the trailing surrogate is not.
///
/// let emojiHigh = cafe.utf16.index(after: utf16Index)
/// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8))
/// // Prints "Optional(String.Index(...))"
///
/// let emojiLow = cafe.utf16.index(after: emojiHigh)
/// print(String.UTF8View.Index(emojiLow, within: cafe.utf8))
/// // Prints "nil"
///
/// - Parameters:
/// - sourcePosition: A position in a `String` or one of its views.
/// - target: The `UTF8View` in which to find the new position.
public init?(_ idx: String.Index, within target: String.UTF8View) {
// Note: This method used to be inlinable until Swift 5.7.
// As a special exception, we allow `idx` to be an UTF-16 index when `self`
// is a UTF-8 string, to preserve compatibility with (broken) code that
// keeps using indices from a bridged string after converting the string to
// a native representation. Such indices are invalid, but returning nil here
// can break code that appeared to work fine for ASCII strings in Swift
// releases prior to 5.7.
guard
let idx = target._guts.ensureMatchingEncodingNoTrap(idx),
idx._encodedOffset <= target._guts.count
else { return nil }
if _slowPath(target._guts.isForeign) {
guard idx._foreignIsWithin(target) else { return nil }
} else {
// All indices that are in range are valid, except sub-scalar UTF-16
// indices pointing at trailing surrogates.
guard idx.transcodedOffset == 0 else { return nil }
}
self = idx
}
}
#if SWIFT_ENABLE_REFLECTION
// Reflection
extension String.UTF8View: CustomReflectable {
/// Returns a mirror that reflects the UTF-8 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
#endif
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex]
///
/// was deduced to be of type `String.UTF8View`. Provide a more-specific
/// Swift-3-only `subscript` overload that continues to produce
/// `String.UTF8View`.
extension String.UTF8View {
public typealias SubSequence = Substring.UTF8View
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UTF8View.SubSequence {
let r = _guts.validateSubscalarRange(r)
return Substring.UTF8View(self, _bounds: r)
}
}
extension String.UTF8View {
/// Copies `self` into the supplied buffer.
///
/// - Precondition: The memory in `self` is uninitialized. The buffer must
/// contain sufficient uninitialized memory to accommodate
/// `source.underestimatedCount`.
///
/// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]`
/// are initialized.
@inlinable @inline(__always)
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) {
guard buffer.baseAddress != nil else {
_preconditionFailure(
"Attempt to copy string contents into nil buffer pointer")
}
guard let written = _guts.copyUTF8(into: buffer) else {
_preconditionFailure(
"Insufficient space allocated to copy string contents")
}
let it = String().utf8.makeIterator()
return (it, buffer.index(buffer.startIndex, offsetBy: written))
}
}
// Foreign string support
extension String.UTF8View {
// Align a foreign UTF-16 index to a valid UTF-8 position. If there is a
// transcoded offset already, this is already a valid UTF-8 position
// (referring to a continuation byte) and returns `idx`. Otherwise, this will
// scalar-align the index. This is needed because we may be passed a
// non-scalar-aligned foreign index from the UTF16View.
@inline(__always)
internal func _utf8AlignForeignIndex(_ idx: String.Index) -> String.Index {
_internalInvariant(_guts.isForeign)
guard idx.transcodedOffset == 0 else { return idx }
return _guts.scalarAlign(idx)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after idx: Index) -> Index {
_internalInvariant(_guts.isForeign)
_internalInvariant(idx._encodedOffset < _guts.count)
let idx = _utf8AlignForeignIndex(idx)
let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar(
startingAt: idx.strippingTranscoding)
let utf8Len = UTF8.width(scalar)
if utf8Len == 1 {
_internalInvariant(idx.transcodedOffset == 0)
return idx.nextEncoded._scalarAligned._knownUTF16
}
// Check if we're still transcoding sub-scalar
if idx.transcodedOffset < utf8Len - 1 {
return idx.nextTranscoded._knownUTF16
}
// Skip to the next scalar
_internalInvariant(idx.transcodedOffset == utf8Len - 1)
return idx.encoded(offsetBy: scalarLen)._scalarAligned._knownUTF16
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before idx: Index) -> Index {
_internalInvariant(_guts.isForeign)
_internalInvariant(idx._encodedOffset <= _guts.count)
let idx = _utf8AlignForeignIndex(idx)
if idx.transcodedOffset != 0 {
_internalInvariant((1...3) ~= idx.transcodedOffset)
return idx.priorTranscoded._knownUTF16
}
let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar(
endingAt: idx.strippingTranscoding)
let utf8Len = UTF8.width(scalar)
return idx.encoded(
offsetBy: -scalarLen
).transcoded(withOffset: utf8Len &- 1)._knownUTF16
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(position idx: Index) -> UTF8.CodeUnit {
_internalInvariant(_guts.isForeign)
let idx = _utf8AlignForeignIndex(idx)
let scalar = _guts.foreignErrorCorrectedScalar(
startingAt: idx.strippingTranscoding).0
let encoded = Unicode.UTF8.encode(scalar)._unsafelyUnwrappedUnchecked
_internalInvariant(idx.transcodedOffset < 1+encoded.count)
return encoded[
encoded.index(encoded.startIndex, offsetBy: idx.transcodedOffset)]
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index {
_internalInvariant(_guts.isForeign)
return _index(i, offsetBy: n)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_internalInvariant(_guts.isForeign)
return _index(i, offsetBy: n, limitedBy: limit)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignDistance(from i: Index, to j: Index) -> Int {
_internalInvariant(_guts.isForeign)
let i = _utf8AlignForeignIndex(i)
let j = _utf8AlignForeignIndex(j)
#if _runtime(_ObjC)
// Currently, foreign means NSString
if let count = _cocoaStringUTF8Count(
_guts._object.cocoaObject,
range: i._encodedOffset ..< j._encodedOffset
) {
// _cocoaStringUTF8Count gave us the scalar aligned count, but we still
// need to compensate for sub-scalar indexing, e.g. if `i` is in the
// middle of a two-byte UTF8 scalar.
let refinedCount = (count - i.transcodedOffset) + j.transcodedOffset
_internalInvariant(refinedCount == _distance(from: i, to: j))
return refinedCount
}
#endif
return _distance(from: i, to: j)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignCount() -> Int {
_internalInvariant(_guts.isForeign)
return _foreignDistance(from: startIndex, to: endIndex)
}
}
extension String.Index {
@usableFromInline @inline(never) // opaque slow-path
@_effects(releasenone)
internal func _foreignIsWithin(_ target: String.UTF8View) -> Bool {
_internalInvariant(target._guts.isForeign)
return self == target._utf8AlignForeignIndex(self)
}
}
extension String.UTF8View {
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
guard _guts.isFastUTF8 else { return nil }
return try _guts.withFastUTF8(body)
}
}
| apache-2.0 | 23b5febb41427a4675ef231eeaea5044 | 32.86201 | 80 | 0.653469 | 4.016367 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.