repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DarrenKong/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/TabLocationView.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
protocol TabLocationViewDelegate {
func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView)
func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapPageOptions(_ tabLocationView: TabLocationView, from button: UIButton)
func tabLocationViewDidLongPressPageOptions(_ tabLocationVIew: TabLocationView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
@discardableResult func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool
func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]?
}
private struct TabLocationViewUX {
static let HostFontColor = UIColor.black
static let BaseURLFontColor = UIColor.gray
static let LocationContentInset = 8
static let URLBarPadding = 4
}
class TabLocationView: UIView {
var delegate: TabLocationViewDelegate?
var longPressRecognizer: UILongPressGestureRecognizer!
var tapRecognizer: UITapGestureRecognizer!
dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor {
didSet { updateTextWithURL() }
}
var url: URL? {
didSet {
let wasHidden = lockImageView.isHidden
lockImageView.isHidden = url?.scheme != "https"
if wasHidden != lockImageView.isHidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
updateTextWithURL()
pageOptionsButton.isHidden = (url == nil)
setNeedsUpdateConstraints()
}
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
let wasHidden = readerModeButton.isHidden
self.readerModeButton.readerModeState = newReaderModeState
readerModeButton.isHidden = (newReaderModeState == ReaderModeState.unavailable)
separatorLine.isHidden = readerModeButton.isHidden
if wasHidden != readerModeButton.isHidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
if !readerModeButton.isHidden {
// Delay the Reader Mode accessibility announcement briefly to prevent interruptions.
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.ReaderModeAvailableVoiceOverAnnouncement)
}
}
}
UIView.animate(withDuration: 0.1, animations: { () -> Void in
if newReaderModeState == ReaderModeState.unavailable {
self.readerModeButton.alpha = 0.0
} else {
self.readerModeButton.alpha = 1.0
}
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
})
}
}
}
lazy var placeholder: NSAttributedString = {
let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home")
return NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.gray])
}()
lazy var urlTextField: UITextField = {
let urlTextField = DisplayTextField()
self.longPressRecognizer.delegate = self
urlTextField.addGestureRecognizer(self.longPressRecognizer)
self.tapRecognizer.delegate = self
urlTextField.addGestureRecognizer(self.tapRecognizer)
// Prevent the field from compressing the toolbar buttons on the 4S in landscape.
urlTextField.setContentCompressionResistancePriority(250, for: .horizontal)
urlTextField.attributedPlaceholder = self.placeholder
urlTextField.accessibilityIdentifier = "url"
urlTextField.accessibilityActionsSource = self
urlTextField.font = UIConstants.DefaultChromeFont
urlTextField.backgroundColor = .clear
// Remove the default drop interaction from the URL text field so that our
// custom drop interaction on the BVC can accept dropped URLs.
if #available(iOS 11, *) {
if let dropInteraction = urlTextField.textDropInteraction {
urlTextField.removeInteraction(dropInteraction)
}
}
return urlTextField
}()
fileprivate lazy var lockImageView: UIImageView = {
let lockImageView = UIImageView(image: UIImage.templateImageNamed("lock_verified"))
lockImageView.isHidden = true
lockImageView.tintColor = UIColor.Defaults.LockGreen
lockImageView.isAccessibilityElement = true
lockImageView.contentMode = .center
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure")
return lockImageView
}()
fileprivate lazy var readerModeButton: ReaderModeButton = {
let readerModeButton = ReaderModeButton(frame: .zero)
readerModeButton.isHidden = true
readerModeButton.addTarget(self, action: #selector(SELtapReaderModeButton), for: .touchUpInside)
readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(SELlongPressReaderModeButton)))
readerModeButton.isAccessibilityElement = true
readerModeButton.imageView?.contentMode = .scaleAspectFit
readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button")
readerModeButton.accessibilityIdentifier = "TabLocationView.readerModeButton"
readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: #selector(SELreaderModeCustomAction))]
return readerModeButton
}()
lazy var pageOptionsButton: ToolbarButton = {
let pageOptionsButton = ToolbarButton(frame: .zero)
pageOptionsButton.setImage(UIImage.templateImageNamed("menu-More-Options"), for: .normal)
pageOptionsButton.isHidden = true
pageOptionsButton.addTarget(self, action: #selector(SELDidPressPageOptionsButton), for: .touchUpInside)
pageOptionsButton.isAccessibilityElement = true
pageOptionsButton.imageView?.contentMode = .center
pageOptionsButton.accessibilityLabel = NSLocalizedString("Page Options Menu", comment: "Accessibility label for the Page Options menu button")
pageOptionsButton.accessibilityIdentifier = "TabLocationView.pageOptionsButton"
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(SELDidLongPressPageOptionsButton))
pageOptionsButton.addGestureRecognizer(longPressGesture)
return pageOptionsButton
}()
lazy var separatorLine: UIView = {
let line = UIView()
line.layer.cornerRadius = 2
line.isHidden = true
return line
}()
override init(frame: CGRect) {
super.init(frame: frame)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(SELlongPressLocation))
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(SELtapLocation))
addSubview(urlTextField)
addSubview(lockImageView)
addSubview(readerModeButton)
addSubview(pageOptionsButton)
addSubview(separatorLine)
lockImageView.snp.makeConstraints { make in
make.size.equalTo(24)
make.centerY.equalTo(self)
make.leading.equalTo(self).offset(9)
}
pageOptionsButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.trailing.equalTo(self)
make.width.equalTo(44)
make.height.equalTo(self)
}
separatorLine.snp.makeConstraints { make in
make.width.equalTo(1)
make.height.equalTo(26)
make.trailing.equalTo(pageOptionsButton.snp.leading)
make.centerY.equalTo(self)
}
readerModeButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.trailing.equalTo(separatorLine.snp.leading).offset(-9)
make.size.equalTo(24)
}
}
override var accessibilityElements: [Any]? {
get {
return [lockImageView, urlTextField, readerModeButton, pageOptionsButton].filter { !$0.isHidden }
}
set {
super.accessibilityElements = newValue
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
urlTextField.snp.remakeConstraints { make in
make.top.bottom.equalTo(self)
if lockImageView.isHidden {
make.leading.equalTo(self).offset(TabLocationViewUX.LocationContentInset)
} else {
make.leading.equalTo(self.lockImageView.snp.trailing).offset(TabLocationViewUX.URLBarPadding)
}
if readerModeButton.isHidden {
make.trailing.equalTo(self.pageOptionsButton.snp.leading).offset(-TabLocationViewUX.URLBarPadding)
} else {
make.trailing.equalTo(self.readerModeButton.snp.leading).offset(-TabLocationViewUX.URLBarPadding)
}
}
super.updateConstraints()
}
func SELtapReaderModeButton() {
delegate?.tabLocationViewDidTapReaderMode(self)
}
func SELlongPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .began {
delegate?.tabLocationViewDidLongPressReaderMode(self)
}
}
func SELDidPressPageOptionsButton(_ button: UIButton) {
delegate?.tabLocationViewDidTapPageOptions(self, from: button)
}
func SELDidLongPressPageOptionsButton(_ recognizer: UILongPressGestureRecognizer) {
delegate?.tabLocationViewDidLongPressPageOptions(self)
}
func SELlongPressLocation(_ recognizer: UITapGestureRecognizer) {
if recognizer.state == .began {
delegate?.tabLocationViewDidLongPressLocation(self)
}
}
func SELtapLocation(_ recognizer: UITapGestureRecognizer) {
delegate?.tabLocationViewDidTapLocation(self)
}
func SELreaderModeCustomAction() -> Bool {
return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false
}
fileprivate func updateTextWithURL() {
if let host = url?.host, AppConstants.MOZ_PUNYCODE {
urlTextField.text = url?.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8())
} else {
urlTextField.text = url?.absoluteString
}
// remove https:// (the scheme) from the url when displaying
if let scheme = url?.scheme, let range = url?.absoluteString.range(of: "\(scheme)://") {
urlTextField.text = url?.absoluteString.replacingCharacters(in: range, with: "")
}
}
}
extension TabLocationView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// If the longPressRecognizer is active, fail all other recognizers to avoid conflicts.
return gestureRecognizer == longPressRecognizer
}
}
extension TabLocationView: AccessibilityActionsSource {
func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? {
if view === urlTextField {
return delegate?.tabLocationViewLocationAccessibilityActions(self)
}
return nil
}
}
extension TabLocationView: Themeable {
func applyTheme(_ theme: Theme) {
backgroundColor = UIColor.TextField.Background.colorFor(theme)
urlTextField.textColor = UIColor.Browser.Tint.colorFor(theme)
readerModeButton.selectedTintColor = UIColor.TextField.ReaderModeButtonSelected.colorFor(theme)
readerModeButton.unselectedTintColor = UIColor.TextField.ReaderModeButtonUnselected.colorFor(theme)
pageOptionsButton.selectedTintColor = UIColor.TextField.PageOptionsSelected.colorFor(theme)
pageOptionsButton.unselectedTintColor = UIColor.TextField.PageOptionsUnselected.colorFor(theme)
pageOptionsButton.tintColor = pageOptionsButton.unselectedTintColor
separatorLine.backgroundColor = UIColor.TextField.Separator.colorFor(theme)
}
}
class ReaderModeButton: UIButton {
var selectedTintColor: UIColor?
var unselectedTintColor: UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
adjustsImageWhenHighlighted = false
setImage(UIImage.templateImageNamed("reader"), for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override open var isHighlighted: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override var tintColor: UIColor! {
didSet {
self.imageView?.tintColor = self.tintColor
}
}
var _readerModeState: ReaderModeState = ReaderModeState.unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .available:
self.isEnabled = true
self.isSelected = false
case .unavailable:
self.isEnabled = false
self.isSelected = false
case .active:
self.isEnabled = true
self.isSelected = true
}
}
}
}
private class DisplayTextField: UITextField {
weak var accessibilityActionsSource: AccessibilityActionsSource?
override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
return accessibilityActionsSource?.accessibilityCustomActionsForView(self)
}
set {
super.accessibilityCustomActions = newValue
}
}
fileprivate override var canBecomeFirstResponder: Bool {
return false
}
}
|
55dcb8dd644b5bb17e55a26d30226883
| 40.414698 | 273 | 0.680905 | false | false | false | false |
iZhang/travel-architect
|
refs/heads/master
|
main/Camera Controller/CameraViewController.swift
|
mit
|
1
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
View controller for selecting images and applying Vision + Core ML processing.
*/
import UIKit
import CoreML
import Vision
import ImageIO
class CameraViewController: UIViewController
{
// MARK: - IBOutlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var classificationLabel: UILabel!
@IBOutlet weak var cameraButton: UIBarButtonItem!
// MARK: - Image Classification
/// - Tag: MLModelSetup
lazy var classificationRequest: VNCoreMLRequest = {
do {
/*
Use the Swift class `Architecture` Core ML generates from the model.
*/
let model = try VNCoreMLModel(for: Architecture().model)
let request = VNCoreMLRequest(model: model, completionHandler: { [weak self] request, error in
self?.processClassifications(for: request, error: error)
})
request.imageCropAndScaleOption = .centerCrop
return request
} catch {
fatalError("Failed to load Vision ML model: \(error)")
}
}()
/// - Tag: PerformRequests
func updateClassifications(for image: UIImage)
{
classificationLabel.text = "Classifying..."
let orientation = CGImagePropertyOrientation(image.imageOrientation)
guard let ciImage = CIImage(image: image) else { fatalError("Unable to create \(CIImage.self) from \(image).") }
DispatchQueue.global(qos: .userInitiated).async {
let handler = VNImageRequestHandler(ciImage: ciImage, orientation: orientation)
do {
try handler.perform([self.classificationRequest])
} catch {
/*
This handler catches general image processing errors. The `classificationRequest`'s
completion handler `processClassifications(_:error:)` catches errors specific
to processing that request.
*/
print("Failed to perform classification.\n\(error.localizedDescription)")
}
}
}
/// Updates the UI with the results of the classification.
/// - Tag: ProcessClassifications
func processClassifications(for request: VNRequest, error: Error?)
{
DispatchQueue.main.async {
guard let results = request.results else {
self.classificationLabel.text = "Unable to classify image.\n\(error!.localizedDescription)"
return
}
// The `results` will always be `VNClassificationObservation`s, as specified by the Core ML model in this project.
let classifications = results as! [VNClassificationObservation]
if classifications.isEmpty {
self.classificationLabel.text = "Nothing recognized."
} else {
// Display top classifications ranked by confidence in the UI.
let topClassifications = classifications.prefix(2)
let descriptions = topClassifications.map { classification in
// Formats the classification for display; e.g. "(0.37) cliff, drop, drop-off".
return String(format: " %.2f%% %@", classification.confidence * 100, classification.identifier)
}
self.classificationLabel.text = "The Architect sees:\n" + descriptions.joined(separator: "\n")
}
}
}
override func viewDidAppear(_ animated: Bool)
{ super.viewDidAppear(animated) }
override func viewWillDisappear(_ animated: Bool)
{ super.viewWillDisappear(animated) }
// MARK: - Photo Actions
@IBAction func takePicture()
{
// Show options for the source picker only if the camera is available.
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
presentPhotoPicker(sourceType: .photoLibrary)
return
}
let photoSourcePicker = UIAlertController()
let takePhoto = UIAlertAction(title: "Take Photo", style: .default) { [unowned self] _ in
self.presentPhotoPicker(sourceType: .camera)
}
let choosePhoto = UIAlertAction(title: "Choose Photo", style: .default) { [unowned self] _ in
self.presentPhotoPicker(sourceType: .photoLibrary)
}
photoSourcePicker.addAction(takePhoto)
photoSourcePicker.addAction(choosePhoto)
photoSourcePicker.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(photoSourcePicker, animated: true)
}
func presentPhotoPicker(sourceType: UIImagePickerControllerSourceType)
{
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = sourceType
present(picker, animated: true)
}
}
extension CameraViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
// MARK: - Handling Image Picker Selection
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
picker.dismiss(animated: true)
// We always expect `imagePickerController(:didFinishPickingMediaWithInfo:)` to supply the original image.
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
updateClassifications(for: image)
}
}
|
769eafc7acbac48dba2da1ac52819fbf
| 38.28169 | 126 | 0.63374 | false | false | false | false |
royratcliffe/Faraday
|
refs/heads/master
|
Sources/Headers+Accept.swift
|
mit
|
1
|
// Faraday Headers+Accept.swift
//
// Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
import Foundation
extension Headers {
public var accept: String? {
get {
return self["Accept"]
}
set(value) {
self["Accept"] = value
}
}
/// Accesses the HTTP Accept header. The header is a comma-delimited string of
/// media ranges, each with an optional quality factor separated from the
/// media range by a semicolon. The `accepts` method (plural) splits the
/// header by commas and trims out any white-space. The result is an array of
/// strings, one for each media range.
public var acceptContentTypes: [String]? {
get {
return accept?.characters.split(separator: ",").map {
String($0).trimmingCharacters(in: CharacterSet.whitespaces)
}
}
set(value) {
accept = value?.joined(separator: ", ")
}
}
/// Adds more type elements to the Accept header. Does not add duplicates;
/// instead, it passes the new elements through a filter in order to remove
/// duplicates and make the acceptable types unique.
public mutating func accepts(contentTypes: [String]) {
guard let oldContentTypes = acceptContentTypes else {
acceptContentTypes = contentTypes
return
}
acceptContentTypes = oldContentTypes + contentTypes.filter { (contentType) -> Bool in
!oldContentTypes.contains(contentType)
}
}
}
|
4f7b764c2b679a8e500df9d9ff5430bd
| 37.910448 | 89 | 0.693517 | false | false | false | false |
fernandomarins/food-drivr-pt
|
refs/heads/master
|
hackathon-for-hunger/Modules/User/Views/ProfileViewController.swift
|
mit
|
1
|
//
// ProfileViewController.swift
// hackathon-for-hunger
//
// Created by Anas Belkhadir on 15/04/2016.
// Copyright © 2016 Hacksmiths. All rights reserved.
// Edits by David Fierstein 11/05/2016
import UIKit
class ProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
var activityIndicator : ActivityIndicatorView!
private let profilePresenter = ProfilePresenter(userService: UserService(), authService: AuthService())
var imageData: NSData?
@IBOutlet weak var userNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var avatarView: UIView!
@IBOutlet weak var avatarImageView: UIImageView!
@IBAction func save(sender: AnyObject) {
updateUser()
}
override func viewDidLoad() {
self.title = "My Profile"
super.viewDidLoad()
profilePresenter.attachView(self)
updateUI()
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(ProfileViewController.avatarTapped(_:)))
avatarView.addGestureRecognizer(tapGestureRecognizer)
avatarView.invalidateIntrinsicContentSize() // let the profile image size be set by constraints, not by the intrinsic size of the photo
avatarView.contentMode = .ScaleAspectFill
avatarImageView.contentMode = .ScaleAspectFill
}
func avatarTapped(img: AnyObject) {
pickAnImageFromAlbum(img)
}
func pickAnImageFromAlbum(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(pickerController, animated: true, completion: nil)
}
//MARK:- Image Picker functions
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
self.dismissViewControllerAnimated(true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
avatarImageView.image = image
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func updateUser() {
var user = UserUpdate()
if emailTextField.text != nil && emailTextField.text != "" {
user.email = emailTextField.text
}
if userNameTextField != nil && userNameTextField.text != "" {
user.name = userNameTextField.text
}
profilePresenter.updateUser(user)
}
func updateUI() {
let currentUser = profilePresenter.getUser()
if currentUser != nil {
userNameTextField.text = currentUser?.name
emailTextField.text = currentUser?.email
}
}
@IBAction func toggleMenu(sender: AnyObject) {
self.slideMenuController()?.openLeft()
}
//MARK: - Text and keyboard function
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//MARK:- Gesture Recognizer functions
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// Don't let tap GR hide textfields if a textfield is being touched for editing
if touch.view == userNameTextField || touch.view == emailTextField || touch.view == passwordTextField {
return false
}
// Anywhere else on the screen, allow the tap gesture recognizer to hideToolBars
return true
}
// Cancels textfield editing when user touches outside the textfield
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if userNameTextField.isFirstResponder() || emailTextField.isFirstResponder() || passwordTextField.isFirstResponder() {
view.endEditing(true)
}
super.touchesBegan(touches, withEvent:event)
}
}
extension ProfileViewController: ProfileView {
func startLoading() {
self.activityIndicator.startAnimating()
}
func finishLoading() {
self.activityIndicator.stopAnimating()
}
func update(didSucceed user: [String: AnyObject]) {
//self.finishLoading()
updateUI()
}
func update(didFail error: NSError) {
//self.finishLoading()
print("Error in saving user profile info: \(error)")
// The new data didn't save, reload the UI with the current data
updateUI()
}
func getUser(didSucceed user: [String: AnyObject]) {
print("getUser: \(user)")
}
func getUser(didFail error: NSError) {
print(error)
}
}
|
fb13796a0bd7c068fb48141df6c33c37
| 31.210191 | 143 | 0.662975 | false | false | false | false |
matheusbc/virtus
|
refs/heads/master
|
VirtusApp/VirtusApp/ViewController/JobsViewController.swift
|
mit
|
1
|
//
// JobsViewController.swift
// VirtusApp
//
// Copyright © 2017 Matheus B Campos. All rights reserved.
//
import UIKit
/// The jobs list view controller.
class JobsViewController: UITableViewController, Loadable {
// MARK: Properties
// The news view model.
let jobsViewModel = JobsViewModel()
override func viewDidLoad() {
super.viewDidLoad()
let loading = self.showLoading(self)
tableView.tableFooterView = UIView()
self.dismissLoading(loading)
}
}
extension JobsViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobsViewModel.getListSize()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Vagas"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = createJobCell(cellForRowAt: indexPath)
cell.textLabel?.text = jobsViewModel.description(cellForRowAt: indexPath.row)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let jobApplication = self.storyboard?.instantiateViewController(withIdentifier: "JobApplicationViewController") as! JobApplicationViewController
jobApplication.jobName = jobsViewModel.description(cellForRowAt: indexPath.row)
navigationController?.pushViewController(jobApplication, animated: true)
}
// MARK: Private methods
/// Create table view cell for job.
private func createJobCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "JobCell", for: indexPath)
}
}
|
a00490e08d05bda83f77aa9e1cfc4d94
| 33.052632 | 152 | 0.71458 | false | false | false | false |
Sherlouk/monzo-vapor
|
refs/heads/master
|
Sources/FeedItem.swift
|
mit
|
1
|
import Foundation
protocol FeedItem {
var type: String { get }
var params: [String: String] { get }
var url: URL? { get }
func validate() throws
}
public struct BasicFeedItem: FeedItem {
var type: String {
return "basic"
}
public var title: String
public var imageUrl: URL
public var url: URL?
public var body: String?
public var options: [BasicFeedItemStyleOptions]
public init(title: String, imageUrl: URL, openUrl: URL? = nil, body: String? = nil, options: [BasicFeedItemStyleOptions] = []) {
self.title = title
self.imageUrl = imageUrl
self.url = openUrl
self.body = body
self.options = options
}
var params: [String: String] {
var builder = [String: String]()
builder["title"] = title
builder["image_url"] = imageUrl.absoluteString
if let body = body {
builder["body"] = body
}
options.forEach {
switch $0 {
case .backgroundColor(let color): builder["background_color"] = color
case .titleColor(let color): builder["title_color"] = color
case .bodyColor(let color): builder["body_color"] = color
}
}
return builder
}
func validate() throws {
if title.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
throw MonzoUsageError.invalidFeedItem
}
}
}
public enum BasicFeedItemStyleOptions {
/// Sets the background color of the feed item. Value should be a HEX code
case backgroundColor(String)
/// Sets the text color of the feed item's title label. Value should be a HEX code
case titleColor(String)
/// Sets the text color of the feed item's body label, if one exists. Value should be a HEX code
case bodyColor(String)
}
|
c8f0efa6568499971f380e874d8b9bee
| 28.123077 | 132 | 0.596936 | false | false | false | false |
nevercry/ShadowVPNiOS
|
refs/heads/master
|
ShadowVPN/QRCodeShareVC.swift
|
gpl-3.0
|
1
|
//
// QRCodeShareVC.swift
// ShadowVPN
//
// Created by Joe on 16/2/11.
// Copyright © 2016年 clowwindy. All rights reserved.
//
import UIKit
import Photos
class QRCodeShareVC: UIViewController {
var configQuery: String?
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "save")
self.title = "Share Configuration"
self.displayQRCodeImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func displayQRCodeImage() {
// show Image
let query: String = self.configQuery!
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(query.dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
let width: CGFloat = 200
let heigth: CGFloat = 200
let x = (self.view.bounds.width - width) / 2
let y = (self.view.bounds.height - heigth) / 2
self.imageView = UIImageView(frame: CGRectMake(x, y, width, heigth))
let codeImage = UIImage(CIImage: (filter?.outputImage)!.imageByApplyingTransform(CGAffineTransformMakeScale(10, 10)))
let iconImage = UIImage(named: "qrcode_avatar")
let rect = CGRectMake(0, 0, codeImage.size.width, codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.drawInRect(rect)
let avatarSize = CGSizeMake(rect.size.width * 0.25, rect.size.height * 0.25)
let avatar_x = (rect.width - avatarSize.width) * 0.5
let avatar_y = (rect.height - avatarSize.height) * 0.5
iconImage!.drawInRect(CGRectMake(avatar_x, avatar_y, avatarSize.width, avatarSize.height))
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// let tapGR = UITapGestureRecognizer(target: self, action: "tapImage:")
// imageView.userInteractionEnabled = true
// imageView.addGestureRecognizer(tapGR)
self.imageView.image = resultImage
self.view.addSubview(self.imageView)
}
// func tapImage(sender: UITapGestureRecognizer) {
// print("image view tapped")
// }
func save() {
// save code image to album
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .Denied, .Restricted:
let alert = UIAlertController(title: "No Permission", message: "You should approve ShadowVPN to access your photos", preferredStyle: UIAlertControllerStyle.Alert)
let settingAction = UIAlertAction(title: "Setup", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let settingURL = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(settingURL!)
})
})
alert.addAction(settingAction)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
default:
UIImageWriteToSavedPhotosAlbum(self.imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
if (error != nil) {
NSLog("%@", error!)
} else {
let alert = UIAlertController(title: "Saved", message: "Image save to Photos", preferredStyle: UIAlertControllerStyle.Alert)
let done = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction) -> Void in
self.navigationController?.popToRootViewControllerAnimated(true)
})
alert.addAction(done)
self.presentViewController(alert, animated: true, completion: nil)
NSLog("saved image to album")
}
}
}
|
98383688a3e66ee737a5f6251cbf0d6c
| 38.081301 | 174 | 0.63678 | false | false | false | false |
bradleypj823/Swift-StackOverFlow
|
refs/heads/master
|
SwiftStackOverFlow/MenuTableViewController.swift
|
gpl-3.0
|
1
|
//
// MenuTableViewController.swift
// SwiftStackOverFlow
//
// Created by Bradley Johnson on 6/26/14.
// Copyright (c) 2014 Bradley Johnson. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
let menuOptions = ["Search Questions","My Profile"]
var profileVC :UIViewController!
var searchAnswersVC : AnswerSearchViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.profileVC = self.storyboard.instantiateViewControllerWithIdentifier("profileVC") as UIViewController
self.searchAnswersVC = self.storyboard.instantiateViewControllerWithIdentifier("searchAnswersVC") as AnswerSearchViewController
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.menuOptions.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView!.dequeueReusableCellWithIdentifier("menuCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = self.menuOptions[indexPath!.row]
return cell
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
switch indexPath.row {
case 0:
self.splitViewController.showDetailViewController(self.searchAnswersVC, sender: self)
case 1:
self.splitViewController.showDetailViewController(self.profileVC, sender: self)
default:
nil
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
|
155e48ba0b8c5070d4a8b3ef93933125
| 35.886957 | 159 | 0.690712 | false | false | false | false |
Constantine-Fry/rebekka
|
refs/heads/master
|
rebekka-demo/Demo/AppDelegate.swift
|
bsd-2-clause
|
1
|
//
// AppDelegate.swift
// Demo
//
// Created by Constantine Fry on 17/05/15.
// Copyright (c) 2015 Constantine Fry. All rights reserved.
//
import UIKit
import RebekkaTouch
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var session: Session!
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var configuration = SessionConfiguration()
configuration.host = "ftp://speedtest.tele2.net"
self.session = Session(configuration: configuration)
testList()
//testDownload()
//testUpload()
//testCreate()
return true
}
func testList() {
self.session.list("/") {
(resources, error) -> Void in
print("List directory with result:\n\(resources), error: \(error)\n\n")
}
}
func testUpload() {
if let URL = NSBundle.mainBundle().URLForResource("TestUpload", withExtension: "png") {
let path = "/upload/\(NSUUID().UUIDString).png"
self.session.upload(URL, path: path) {
(result, error) -> Void in
print("Upload file with result:\n\(result), error: \(error)\n\n")
}
}
}
func testDownload() {
self.session.download("/1MB.zip") {
(fileURL, error) -> Void in
print("Download file with result:\n\(fileURL), error: \(error)\n\n")
if let fileURL = fileURL {
do {
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
} catch let error as NSError {
print("Error: \(error)")
}
}
}
}
func testCreate() {
let name = NSUUID().UUIDString
self.session.createDirectory("/upload/\(name)") {
(result, error) -> Void in
print("Create directory with result:\n\(result), error: \(error)")
}
}
}
|
0d60bbf5c1fd6a7f95bd458cea3d0420
| 27.666667 | 95 | 0.534436 | false | true | false | false |
Piwigo/Piwigo-Mobile
|
refs/heads/master
|
piwigo/Settings/Help/Help02ViewController.swift
|
mit
|
1
|
//
// Help02ViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 30/11/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
import UIKit
import piwigoKit
class Help02ViewController: UIViewController {
@IBOutlet weak var legendTop: UILabel!
@IBOutlet weak var imageViewTop: UIImageView!
@IBOutlet weak var legendBot: UILabel!
@IBOutlet weak var imageViewBot: UIImageView!
private let helpID: UInt16 = 0b00000000_00000010
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Initialise mutable attributed strings
let legendTopAttributedString = NSMutableAttributedString(string: "")
let legendBotAttributedString = NSMutableAttributedString(string: "")
// Title of legend above images
let titleString = "\(NSLocalizedString("help02_header", comment: "Background Uploading"))\n"
let titleAttributedString = NSMutableAttributedString(string: titleString)
titleAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontBold() : UIFont.piwigoFontSemiBold(), range: NSRange(location: 0, length: titleString.count))
legendTopAttributedString.append(titleAttributedString)
// Comment below title
var textString = "\(NSLocalizedString("help02_text3", comment: "(requires the uploadAsync extension or Piwigo 11)"))\n"
var textAttributedString = NSMutableAttributedString(string: textString)
textAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontSmall() : UIFont.piwigoFontTiny(), range: NSRange(location: 0, length: textString.count))
legendTopAttributedString.append(textAttributedString)
// Text of legend above images
textString = NSLocalizedString("help02_text", comment: "Select photos/videos, tap Upload")
textAttributedString = NSMutableAttributedString(string: textString)
textAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontNormal() : UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count))
legendTopAttributedString.append(textAttributedString)
// Set legend at top of screen
legendTop.attributedText = legendTopAttributedString
// Text of legend between images
textString = NSLocalizedString("help02_text2", comment: "Plug the device to its charger and let iOS launch the uploads whenever appropriate.")
textAttributedString = NSMutableAttributedString(string: textString)
textAttributedString.addAttribute(.font, value: view.bounds.size.width > 320 ? UIFont.piwigoFontNormal() : UIFont.piwigoFontSmall(), range: NSRange(location: 0, length: textString.count))
legendBotAttributedString.append(textAttributedString)
// Set legend
legendBot.attributedText = legendBotAttributedString
// Set top image view
guard let topImageUrl = Bundle.main.url(forResource: "help02-top", withExtension: "png") else {
fatalError("!!! Could not find help02-top image !!!")
}
imageViewTop.layoutIfNeeded() // Ensure imageView is in its final size.
let topImageSize = imageViewTop.bounds.size
let topImageScale = imageViewTop.traitCollection.displayScale
imageViewTop.image = ImageUtilities.downsample(imageAt: topImageUrl, to: topImageSize, scale: topImageScale)
// Set bottom image view
guard let botImageUrl = Bundle.main.url(forResource: "help02-bot", withExtension: "png") else {
fatalError("!!! Could not find help02-bot image !!!")
}
imageViewBot.layoutIfNeeded() // Ensure imageView is in its final size.
let botImageSize = imageViewBot.bounds.size
let botImageScale = imageViewBot.traitCollection.displayScale
imageViewBot.image = ImageUtilities.downsample(imageAt: botImageUrl, to: botImageSize, scale: botImageScale)
// Remember that this view was watched
AppVars.shared.didWatchHelpViews = AppVars.shared.didWatchHelpViews | helpID
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set colors, fonts, etc.
applyColorPalette()
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Legend color
legendTop.textColor = .piwigoColorText()
legendBot.textColor = .piwigoColorText()
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
}
|
d25d4cb9e0c8c4e62f7a9f1d7e8eb2b4
| 47.028846 | 198 | 0.698298 | false | false | false | false |
ricobeck/KFAboutWindow
|
refs/heads/master
|
Classes/osx/ColoredButton.swift
|
mit
|
1
|
//
// ColoredButton.swift
// KFAboutWindowPreview
//
// Created by Gunnar Herzog on 22/09/2016.
// Copyright © 2016 KF Interactive. All rights reserved.
//
import AppKit
@available(OSX 10.10, *)
public class ColoredButton: NSButton {
@objc public var color: NSColor = .textColor {
didSet {
redraw()
}
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
wantsLayer = true
layerContentsRedrawPolicy = .onSetNeedsDisplay
layer?.cornerRadius = 10
layer?.borderWidth = 1.0
redraw()
}
public override var title: String {
didSet {
redraw()
}
}
private func redraw() {
guard let font = font else { return }
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = .center
attributedTitle = NSAttributedString(string: title, attributes: [.font: font, .paragraphStyle: paragraphStyle, .foregroundColor: color])
}
override public var wantsUpdateLayer:Bool {
return true
}
override public func updateLayer() {
if isHighlighted {
layer?.backgroundColor = color.lighter.cgColor
} else {
layer?.backgroundColor = nil
}
layer?.borderColor = color.cgColor
super.updateLayer()
}
override public var intrinsicContentSize: NSSize {
let width = attributedTitle.size().width
var size = super.intrinsicContentSize
size.width = width + 3.0 * (layer?.cornerRadius ?? 0)
return size
}
}
extension NSColor {
var lighter: NSColor {
return withAlphaComponent(0.15)
}
}
|
80c03d3656635f4e002b6914b2702761
| 23.873239 | 144 | 0.609287 | false | false | false | false |
CodaFi/swift
|
refs/heads/master
|
test/IRGen/multi_file_resilience.swift
|
apache-2.0
|
8
|
// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend -emit-module -enable-library-evolution \
// RUN: -emit-module-path=%t/resilient_struct.swiftmodule \
// RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -module-name main -I %t -emit-ir -primary-file %s %S/Inputs/OtherModule.swift | %FileCheck %s -DINT=i%target-ptrsize
// Check that we correctly handle resilience when parsing as SIL + SIB.
// RUN: %target-swift-frontend -emit-sib -module-name main %S/Inputs/OtherModule.swift -I %t -o %t/other.sib
// RUN: %target-swift-frontend -emit-silgen -module-name main -primary-file %s %S/Inputs/OtherModule.swift -I %t -o %t/main.sil
// RUN: %target-swift-frontend -emit-ir -module-name main -primary-file %t/main.sil %t/other.sib -I %t | %FileCheck %s -DINT=i%target-ptrsize
// This is a single-module version of the test case in
// multi_module_resilience.
// rdar://39763787
// CHECK-LABEL: define {{(dllexport |protected )?}}swiftcc void @"$s4main7copyFoo3fooAA0C0VAE_tF"
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s4main3FooVMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[VWT:%.*]] = load i8**,
// Allocate 'copy'.
// CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK: [[SIZE:%.*]] = load [[INT]], [[INT]]* [[SIZE_ADDR]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, [[INT]] [[SIZE]],
// CHECK: [[COPY:%.*]] = bitcast i8* [[ALLOCA]] to [[FOO:%T4main3FooV]]*
// Perform 'initializeWithCopy' via the VWT instead of trying to inline it.
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[T1:%.*]] = load i8*, i8** [[T0]],
// CHECK: [[COPYFN:%.*]] = bitcast i8* [[T1]] to %swift.opaque* (%swift.opaque*, %swift.opaque*, %swift.type*)*
// CHECK: [[DEST:%.*]] = bitcast [[FOO]]* [[COPY]] to %swift.opaque*
// CHECK: [[SRC:%.*]] = bitcast [[FOO]]* %1 to %swift.opaque*
// CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]])
// Perform 'initializeWithCopy' via the VWT.
// CHECK: [[DEST:%.*]] = bitcast [[FOO]]* %0 to %swift.opaque*
// CHECK: [[SRC:%.*]] = bitcast [[FOO]]* [[COPY]] to %swift.opaque*
// CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]])
public func copyFoo(foo: Foo) -> Foo {
let copy = foo
return copy
}
|
27ed22da610d25072fdfc5bf3690288c
| 59.44186 | 147 | 0.636014 | false | false | false | false |
peacemoon/ios-snapshot-test-case
|
refs/heads/master
|
FBSnapshotTestCase/SwiftSupport.swift
|
mit
|
1
|
/*
* Copyright (c) 2015-2018, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#if swift(>=3)
public extension FBSnapshotTestCase {
public func FBSnapshotVerifyView(_ view: UIView, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
FBSnapshotVerifyViewOrLayer(view, identifier: identifier, suffixes: suffixes, tolerance: tolerance, file: file, line: line)
}
public func FBSnapshotVerifyLayer(_ layer: CALayer, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
FBSnapshotVerifyViewOrLayer(layer, identifier: identifier, suffixes: suffixes, tolerance: tolerance, file: file, line: line)
}
private func FBSnapshotVerifyViewOrLayer(_ viewOrLayer: AnyObject, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
let envReferenceImageDirectory = self.getReferenceImageDirectory(withDefault: FB_REFERENCE_IMAGE_DIR)
var error: NSError?
var comparisonSuccess = false
if let envReferenceImageDirectory = envReferenceImageDirectory {
for suffix in suffixes {
let referenceImagesDirectory = "\(envReferenceImageDirectory)\(suffix)"
if viewOrLayer.isKind(of: UIView.self) {
do {
try compareSnapshot(of: viewOrLayer as! UIView, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: tolerance)
comparisonSuccess = true
} catch let error1 as NSError {
error = error1
comparisonSuccess = false
}
} else if viewOrLayer.isKind(of: CALayer.self) {
do {
try compareSnapshot(of: viewOrLayer as! CALayer, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: tolerance)
comparisonSuccess = true
} catch let error1 as NSError {
error = error1
comparisonSuccess = false
}
} else {
assertionFailure("Only UIView and CALayer classes can be snapshotted")
}
assert(recordMode == false, message: "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file: file, line: line)
if comparisonSuccess || recordMode {
break
}
assert(comparisonSuccess, message: "Snapshot comparison failed: \(String(describing: error))", file: file, line: line)
}
} else {
XCTFail("Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.")
}
}
func assert(_ assertion: Bool, message: String, file: StaticString, line: UInt) {
if !assertion {
XCTFail(message, file: file, line: line)
}
}
}
#else
public extension FBSnapshotTestCase {
public func FBSnapshotVerifyView(view: UIView, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
FBSnapshotVerifyViewOrLayer(view, identifier: identifier, suffixes: suffixes, tolerance: tolerance, file: file, line: line)
}
public func FBSnapshotVerifyLayer(layer: CALayer, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
FBSnapshotVerifyViewOrLayer(layer, identifier: identifier, suffixes: suffixes, tolerance: tolerance, file: file, line: line)
}
private func FBSnapshotVerifyViewOrLayer(viewOrLayer: AnyObject, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
let envReferenceImageDirectory = self.getReferenceImageDirectoryWithDefault(FB_REFERENCE_IMAGE_DIR)
var error: NSError?
var comparisonSuccess = false
if let envReferenceImageDirectory = envReferenceImageDirectory {
for suffix in suffixes {
let referenceImagesDirectory = "\(envReferenceImageDirectory)\(suffix)"
if viewOrLayer.isKindOfClass(UIView) {
do {
try compareSnapshotOfView(viewOrLayer as! UIView, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: tolerance)
comparisonSuccess = true
} catch let error1 as NSError {
error = error1
comparisonSuccess = false
}
} else if viewOrLayer.isKindOfClass(CALayer) {
do {
try compareSnapshotOfLayer(viewOrLayer as! CALayer, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: tolerance)
comparisonSuccess = true
} catch let error1 as NSError {
error = error1
comparisonSuccess = false
}
} else {
assertionFailure("Only UIView and CALayer classes can be snapshotted")
}
assert(recordMode == false, message: "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file: file, line: line)
if comparisonSuccess || recordMode {
break
}
assert(comparisonSuccess, message: "Snapshot comparison failed: \(error)", file: file, line: line)
}
} else {
XCTFail("Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.")
}
}
func assert(assertion: Bool, message: String, file: StaticString, line: UInt) {
if !assertion {
XCTFail(message, file: file, line: line)
}
}
}
#endif
|
5bbc7b9ca9ad5ddf74a1f29a8f5cd989
| 48.308943 | 231 | 0.683594 | false | true | false | false |
Vanlol/MyYDW
|
refs/heads/master
|
SwiftCocoa/Resource/Discover/Controller/WKCommunityMsgViewController.swift
|
apache-2.0
|
1
|
//
// WKCommunityMsgViewController.swift
// ydzbapp-hybrid
//
// Created by admin on 2017/8/7.
// Copyright © 2017年 银多资本. All rights reserved.
//
import UIKit
import WebKit
class WKCommunityMsgViewController: UIViewController {
//结果数据
//fileprivate lazy var comsg:CommMesgModel = CommMesgModel()
//第一步:web调用我的setData方法,给web返回一个字符串.
var dataStr = ""
//let bbsService = FinderService.getInstance
//let realmU = RealmU.getInstance
var userContent:WKUserContentController!
lazy var webView:WKWebView = {
let config = WKWebViewConfiguration()
let userCon = WKUserContentController()
userCon.add(self, name: "JSMethod")
config.userContentController = userCon
self.userContent = userCon
let vi = WKWebView(frame: CGRect.zero, configuration: config)
vi.translatesAutoresizingMaskIntoConstraints = false
vi.navigationDelegate = self
return vi
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
initLeftBarItem()
initView()
loadUrl()
loadData()
}
//MARK: 初始化导航栏
func initLeftBarItem() {
navigationController!.setNavigationBarHidden(false, animated: true)
let negativeSpacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
negativeSpacer.width = -8
let backBtn = UIButton()
let backImage = UIImage(named: "4_nav_return_icon")
backBtn.frame = CGRect(x: 0, y: 0, width: backImage!.size.width, height: backImage!.size.height)
backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
backBtn.setImage(backImage, for: UIControlState.normal)
backBtn.addTarget(self, action: #selector(backClick), for: UIControlEvents.touchUpInside)
let backBtnItem = UIBarButtonItem(customView: backBtn)
navigationItem.leftBarButtonItems = [negativeSpacer, backBtnItem]
}
//MARK: 返回
func backClick() {
dismiss(animated: true, completion: nil)
}
//MARK: 初始化view
func initView() {
view.addSubview(webView)
let leading = NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailing = NSLayoutConstraint(item: webView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let top = NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0.0)
let bottom = NSLayoutConstraint(item: webView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0.0)
view.addConstraints([leading,trailing,top,bottom])
}
//MARK: 加载url
func loadUrl(){
webView.load(URLRequest(url: URL(string: W.BBS_MESG_WEB + U.getMobile()!)!))
}
//MARK: 加载评论数,回复数等
func loadData() {
// bbsService.loadMessageData { (data) in
// if let rms = data as? CommMesgModel {
// self.comsg = rms
// let rep = self.realmU.getCommunityReplyRedPoint().reply_id
// let com = self.realmU.getCommunityCommunityRedPoint().comments_id
// var results = [String]()
// if rms.comments_id == com {
// results.append("false")
// }else{
// results.append("true")
// }
// if rms.reply_id == rep {
// results.append("false")
// }else{
// results.append("true")
// }
// self.dataStr = results.joined(separator: ",")
// }
// }
}
/**
* 注销方法
*/
deinit {
userContent.removeScriptMessageHandler(forName: "JSMethod")
}
}
extension WKCommunityMsgViewController:WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
Print.dlog(userContentController)
Print.dlog(message.name)
}
}
extension WKCommunityMsgViewController:WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Print.dlog("webView --- didFinish")
webView.evaluateJavaScript("app.showRed('" + self.dataStr + "')", completionHandler: { (data, error) in
Print.dlog(data as Any)
Print.dlog(error as Any)
})
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
Print.dlog("webView --- didStartProvisionalNavigation")
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
Print.dlog("webView --- didFail")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
Print.dlog(error)
Print.dlog("webView --- didFailProvisionalNavigation")
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
Print.dlog("webView --- didReceiveServerRedirectForProvisionalNavigation")
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
Print.dlog("webView --- decidePolicyFornavigationAction")
Print.dlog((navigationAction.request.url?.absoluteString)!)
Print.dlog((navigationAction.request.url)!)
decisionHandler(.allow)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
Print.dlog("webView --- decidePolicyFornavigationResponse")
decisionHandler(.allow)
}
/*
*拆分参数数据,上传购买数据
*返回(类型,外网地址,产品名称)
*/
func splitParameter(params:String) -> (String, String, String, String, String, String, String, String, String, String, String, String, String){
var parm = (title: "", thumburl: "", gotourl: "", description: "", addr: "",arrow: "",numbers: "", msg:"", share:"", help:"", rightText:"", id:"", url:"")
_ = (params as NSString).range(of: "?")
let result = params.components(separatedBy: "?").last
let arr = result?.components(separatedBy: "&")
for str in arr! {
let ss = str.components(separatedBy: "=")
if ss.first! == "title" {
parm.title = ss.last!
}else if ss.first! == "thumburl" {
parm.thumburl = ss.last!
}else if ss.first! == "gotourl" {
parm.gotourl = ss.last!
}else if ss.first! == "description" {
parm.description = ss.last!
}else if ss.first! == "addr" {
parm.addr = ss.last!
}else if ss.first! == "arrow" {
parm.arrow = ss.last!
}else if ss.first! == "numbers" {
parm.numbers = ss.last!
}else if ss.first! == "msg" {
parm.msg = ss.last!
}else if ss.first! == "share" {
parm.share = ss.last!
}else if ss.first! == "help" {
parm.help = ss.last!
}else if ss.first! == "cname" {
parm.rightText = ss.last!
}else if ss.first! == "id" {
parm.id = ss.last!
}else if ss.first! == "comment" {
parm.url = ss.last!
}
}
return parm
}
}
|
2fbbaf9bdfe29d7ed24f9abfa20ae62d
| 36.774648 | 165 | 0.601665 | false | false | false | false |
February12/YLPhotoBrowser
|
refs/heads/master
|
Sources/YLDrivenInteractive.swift
|
mit
|
1
|
//
// YLDrivenInteractive.swift
// YLPhotoBrowser
//
// Created by yl on 2017/7/25.
// Copyright © 2017年 February12. All rights reserved.
//
import UIKit
class YLDrivenInteractive: UIPercentDrivenInteractiveTransition {
var transitionOriginalImgFrame: CGRect = CGRect.zero
var transitionBrowserImgFrame: CGRect = CGRect.zero
var transitionImage: UIImage?
var transitionImageView: UIView?
var originalCoverViewBG: UIColor?
var gestureRecognizer: UIPanGestureRecognizer? {
didSet {
gestureRecognizer?.addTarget(self, action: #selector(YLDrivenInteractive.gestureRecognizeDidUpdate(_:)))
}
}
private var transitionContext: UIViewControllerContextTransitioning?
private var blackBgView: UIView?
private var fromView: UIView?
private var toView: UIView?
private var originalCoverView: UIView?
private var isFirst = true
@objc func gestureRecognizeDidUpdate(_ gestureRecognizer: UIPanGestureRecognizer) {
if transitionContext == nil {
return
}
let translation = gestureRecognizer.translation(in: gestureRecognizer.view?.superview)
let window = UIApplication.shared.keyWindow
var scale = 1 - translation.y / (window?.frame.height ?? UIScreen.main.bounds.height)
scale = scale > 1 ? 1:scale
scale = scale < 0 ? 0:scale
if isFirst {
beginInterPercent()
isFirst = false
}
switch gestureRecognizer.state {
case .began:
// 进不来
break
case .changed:
update(scale)
updateInterPercent(scale)
break
case .ended:
if translation.y <= 80 {
cancel()
interPercentCancel()
}else {
finish()
interPercentFinish()
}
break
default:
cancel()
interPercentCancel()
break
}
}
func beginInterPercent() {
// 转场过渡的容器view
if let containerView = self.transitionContext?.containerView {
// ToVC
let toViewController = transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.to)
toView = toViewController?.view
toView?.isHidden = false
containerView.addSubview(toView!)
originalCoverView = UIView.init(frame: transitionOriginalImgFrame)
originalCoverView?.backgroundColor = originalCoverViewBG
containerView.addSubview(originalCoverView!)
// 有渐变的黑色背景
blackBgView = UIView.init(frame: containerView.bounds)
blackBgView?.backgroundColor = PhotoBrowserBG
blackBgView?.isHidden = false
containerView.addSubview(blackBgView!)
// fromVC
let fromViewController = transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.from)
fromView = fromViewController?.view
fromView?.backgroundColor = UIColor.clear
fromView?.isHidden = false
containerView.addSubview(fromView!)
}
}
func updateInterPercent(_ scale: CGFloat) {
blackBgView?.alpha = scale * scale * scale
}
func interPercentCancel() {
gestureRecognizer?.removeTarget(self, action: #selector(YLDrivenInteractive.gestureRecognizeDidUpdate(_:)))
gestureRecognizer = nil
isFirst = true
let transitionContext = self.transitionContext
fromView?.backgroundColor = PhotoBrowserBG
blackBgView?.removeFromSuperview()
originalCoverView?.removeFromSuperview()
transitionContext?.completeTransition(!(transitionContext?.transitionWasCancelled)!)
}
func interPercentFinish() {
gestureRecognizer?.removeTarget(self, action: #selector(YLDrivenInteractive.gestureRecognizeDidUpdate(_:)))
gestureRecognizer = nil
fromView?.isHidden = true
// 转场过渡的容器view
if let containerView = self.transitionContext?.containerView {
// 过度的图片
let transitionImgView = transitionImageView ?? UIImageView.init(image: transitionImage)
transitionImgView.frame = transitionBrowserImgFrame
transitionImageView?.layoutIfNeeded()
containerView.addSubview(transitionImgView)
if transitionOriginalImgFrame == CGRect.zero ||
(transitionImage == nil && transitionImageView == nil) {
UIView.animate(withDuration: 0.3, animations: { [weak self] in
transitionImgView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
transitionImgView.alpha = 0
self?.blackBgView?.alpha = 0
}, completion: { [weak self] (finished:Bool) in
self?.blackBgView?.removeFromSuperview()
self?.originalCoverView?.removeFromSuperview()
transitionImgView.removeFromSuperview()
self?.transitionContext?.completeTransition(!(self?.transitionContext?.transitionWasCancelled)!)
})
return
}
UIView.animate(withDuration: 0.3, animations: { [weak self] in
transitionImgView.frame = (self?.transitionOriginalImgFrame)!
self?.transitionImageView?.layoutIfNeeded()
self?.blackBgView?.alpha = 0
}) { [weak self] (finished: Bool) in
self?.blackBgView?.removeFromSuperview()
self?.originalCoverView?.removeFromSuperview()
transitionImgView.removeFromSuperview()
self?.transitionContext?.completeTransition(!(self?.transitionContext?.transitionWasCancelled)!)
}
}
}
override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
}
}
|
5e907c9a03b9227f48bdddc66ccbb220
| 33.586387 | 121 | 0.574781 | false | false | false | false |
Gaea-iOS/FoundationExtension
|
refs/heads/master
|
Example/FoundationExtension/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// FoundationExtension
//
// Created by wangxiaotao on 07/07/2017.
// Copyright (c) 2017 wangxiaotao. All rights reserved.
//
import UIKit
import FoundationExtension
class ViewController: UIViewController {
@IBOutlet weak var barButtomItem: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let button = UIBarButtonItem(image: UIImage(named: "QQ20170720-0")!, style: .plain, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = button
button.markValue = "5"
navigationController?.tabBarItem.markType = .number
navigationController?.tabBarItem.markValue = "56"
// tabBarItem.badgeValue = "558"
barButtomItem?.markType = .dot
barButtomItem?.markValue = "6"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func clickType1( sender: UIButton) {
let sender = sender
navigationController?.tabBarItem.markType = .dot
sender.markValue = "5"
}
@IBAction func clickType2(sender: Any) {
navigationController?.tabBarItem.markType = .number
}
@IBAction func clickNumber1(sender: Any) {
navigationController?.tabBarItem.markPosition = .topRight(.zero)
}
@IBAction func clickNumber2(sender: Any) {
navigationController?.tabBarItem.markPosition = .topLeft(.zero)
}
@IBAction func clickColor1(sender: Any) {
navigationController?.tabBarItem.markBackgroundColor = .cyan
navigationController?.tabBarItem.markNumberColor = .red
}
@IBAction func clickColor2(sender: Any) {
navigationController?.tabBarItem.markBackgroundColor = .red
navigationController?.tabBarItem.markNumberColor = .cyan
}
}
|
d8d3032732f73b89733a12ac584ba12a
| 28.271429 | 117 | 0.652025 | false | false | false | false |
LOTUM/EventHub
|
refs/heads/master
|
EventHub/ApplicationState.swift
|
apache-2.0
|
1
|
/*
Copyright (c) 2017 LOTUM GmbH
Licensed under Apache License v2.0
See https://github.com/LOTUM/EventHub/blob/master/LICENSE for license information
*/
import UIKit
public enum ApplicationStatus: String, CustomStringConvertible {
case active, inactive, background
public var description: String { return rawValue }
fileprivate init(applicationState state: UIApplicationState) {
switch state {
case .active: self = .active
case .inactive: self = .inactive
case .background: self = .background
}
}
}
final public class ApplicationState {
public typealias ListenerBlock = (ApplicationStatus, ApplicationStatus)->Void
//MARK: Public
public static let shared = ApplicationState()
public var callbackQueue = DispatchQueue.main
public func addChangeListener(_ listener: @escaping (ApplicationStatus)->Void) -> Disposable {
let completeListener: ListenerBlock = { (newStatus, oldStatus) in listener(newStatus) }
defer { fire(listener: completeListener) }
return hub.on("change", action: completeListener)
}
public func addChangeListener(_ listener: @escaping ListenerBlock) -> Disposable {
defer { fire(listener: listener) }
return hub.on("change", action: listener)
}
//MARK: Private
private let hub = EventHub<String, (ApplicationStatus, ApplicationStatus)>()
private var applicationState: UIApplicationState {
didSet {
if applicationState != oldValue {
fire(newState: applicationState, oldState: oldValue)
}
}
}
private init() {
applicationState = UIApplication.shared.applicationState
registerLifecycleEvents()
}
private func registerLifecycleEvents() {
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationWillEnterForeground,
object: nil)
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationDidBecomeActive,
object: nil)
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationWillResignActive,
object: nil)
NotificationCenter
.default
.addObserver(self,
selector: #selector(lifecycleDidChange),
name: .UIApplicationDidEnterBackground,
object: nil)
}
@objc private func lifecycleDidChange(notification: Notification) {
updateState()
}
private func updateState() {
applicationState = UIApplication.shared.applicationState
DispatchQueue.main.async {
self.applicationState = UIApplication.shared.applicationState
}
}
private func fireApplicationEvent(_ event: (ApplicationStatus, ApplicationStatus)) {
hub.emit("change", on: callbackQueue, with: event)
}
private func fire(listener: ListenerBlock? = nil) {
fire(newState: applicationState, oldState: applicationState, toListener: listener)
}
private func fire(newState: UIApplicationState,
oldState: UIApplicationState,
toListener: ListenerBlock? = nil)
{
let payload = (ApplicationStatus(applicationState: newState), ApplicationStatus(applicationState: oldState))
if let listener = toListener {
listener(payload.0, payload.1)
} else {
fireApplicationEvent(payload)
}
}
}
|
e4cfe99f09572a4819813422189e7d27
| 29.851563 | 116 | 0.604963 | false | false | false | false |
mohammedDehairy/MDDijkstraSwift
|
refs/heads/master
|
MDDijkstra-swift/MDRouteNode.swift
|
mit
|
1
|
//
// MDRouteNode.swift
// MDDijkstra-swift
//
// Created by mohamed mohamed El Dehairy on 12/10/16.
// Copyright © 2016 mohamed El Dehairy. All rights reserved.
//
import UIKit
public class MDRouteNode: NSObject {
public let graphNodeIndex : Int
public let weight : Double
public var nextNode : MDRouteNode?
internal var visited = false
init(graphNodeIndex : Int,weight : Double) {
self.graphNodeIndex = graphNodeIndex
self.weight = weight
super.init()
}
}
extension MDRouteNode : Comparable{
public static func <(lhs : MDRouteNode, rhs : MDRouteNode)->Bool{
return lhs.weight < rhs.weight
}
public static func ==(lhs : MDRouteNode, rhs : MDRouteNode)->Bool{
return lhs.weight == rhs.weight
}
}
|
e3999833a5236b4eaff30c6b3ce1a590
| 23.78125 | 70 | 0.655738 | false | false | false | false |
carambalabs/CarambaKit
|
refs/heads/master
|
CarambaKit/Classes/Networking/Base/Session/SessionRepository.swift
|
mit
|
1
|
import Foundation
import KeychainSwift
public class SessionRepository {
// MARK: - Attributes
private let name: String
private let keychain: KeychainSwift
// MARK: - Init
public init(name: String) {
self.name = name
self.keychain = KeychainSwift()
}
// MARK: - Public
public func save(session: Session) {
let accessToken = session.accessToken
let refreshToken = session.refreshToken
self.keychain.set(accessToken, forKey: self.accessTokenKey())
self.keychain.set(refreshToken, forKey: self.refreshTokenKey())
}
public func fetch() -> Session? {
guard let accessToken = self.keychain.get(self.accessTokenKey()) else { return nil }
guard let refreshToken = self.keychain.get(self.refreshTokenKey()) else { return nil }
return Session(accessToken: accessToken, refreshToken: refreshToken)
}
public func clear() {
self.keychain.delete(self.accessTokenKey())
self.keychain.delete(self.refreshTokenKey())
}
// MARK: - Private
private func accessTokenKey() -> String {
return "\(self.name)_access_token"
}
private func refreshTokenKey() -> String {
return "\(self.name)_refresh_token"
}
}
|
a3f58d8282e1289b31d9e5899bbeb22d
| 25.479167 | 94 | 0.649095 | false | false | false | false |
nghiaphunguyen/NKit
|
refs/heads/master
|
NKit/Demo/TestTransitionViewController.swift
|
mit
|
1
|
//
// TestTransitionViewController.swift
// NKit
//
// Created by Nghia Nguyen on 3/22/17.
// Copyright © 2017 Nghia Nguyen. All rights reserved.
//
import UIKit
extension NKPresentationTransition {
static var popupTransition: NKPresentationTransition {
return NKPresentationTransition(presentAnimator: NKAnimator.present(duration: 3, animations: { content in
content.toView.transform = CGAffineTransform.init(scaleX: 0, y: 0)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: UIView.AnimationOptions.curveEaseOut, animations: {
content.toView.transform = CGAffineTransform.init(scaleX: 1, y: 1)
}, completion: {
content.completeTransition(didComplete: $0)
})
}), dismissAnimator: nil, controller: NKPresentationController(options: [.DimViewColor(UIColor.black.withAlphaComponent(0.5)), .TapOutsideToDismiss], sizeOfPresentedView: CGSize(width: 120, height: 120)))
}
}
class TestTransitionViewController: UIViewController {
let transition = NKPresentationTransition.popupTransition
override func loadView() {
super.loadView()
self.view.backgroundColor = UIColor.blue
self.view.nk_addSubview(UIButton()) {
$0.setTitle("tapMe", for: .normal)
$0.snp.makeConstraints({ (make) in
make.center.equalToSuperview()
})
$0.rx.tap.bindNext { [unowned self] in
let viewController = AlertViewController()
viewController.transitioningDelegate = self.transition
viewController.modalPresentationStyle = .custom
self.present(viewController, animated: true, completion: nil)
}.addDisposableTo(self.nk_disposeBag)
}
}
}
extension TestTransitionViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.transition.presentAnimator
}
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return self.transition.controller
}
}
class AlertViewController: UIViewController {
override func loadView() {
super.loadView()
print("transition delegate = \(self.transitioningDelegate)")
self.view.backgroundColor = UIColor.red
}
}
|
455a417891999026063502f7a7649042
| 38.761194 | 212 | 0.679054 | false | false | false | false |
lifesum/configsum
|
refs/heads/master
|
sdk/ios/Configsum/CodableExtensions/Metadata.swift
|
mit
|
1
|
//
// JSON.swift
// Configsum
//
// Created by Michel Tabari on 2017-10-17.
// From https://github.com/zoul/generic-json-swift
import Foundation
public enum Metadata {
case string(String)
case number(Float)
case object([String:Metadata])
case array([Metadata])
case bool(Bool)
case null
}
public enum JSONError: Swift.Error {
case decodingError
}
extension Metadata: Equatable {
public static func == (lhs: Metadata, rhs: Metadata) -> Bool {
switch (lhs, rhs) {
case (.string(let s1), .string(let s2)):
return s1 == s2
case (.number(let n1), .number(let n2)):
return n1 == n2
case (.object(let o1), .object(let o2)):
return o1 == o2
case (.array(let a1), .array(let a2)):
return a1 == a2
case (.bool(let b1), .bool(let b2)):
return b1 == b2
case (.null, .null):
return true
default:
return false
}
}
}
extension Metadata: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .string(let str):
return str.debugDescription
case .number(let num):
return num.debugDescription
case .bool(let bool):
return bool.description
case .null:
return "null"
default:
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted]
return try! String(data: encoder.encode(self), encoding: .utf8)!
}
}
}
|
82443c48f8179ba03a59871a09ed1434
| 24.238095 | 76 | 0.557862 | false | false | false | false |
BGDigital/mckuai2.0
|
refs/heads/master
|
mckuai/mckuai/Search/SearchUserCell.swift
|
mit
|
1
|
//
// SearchUserCell.swift
// mckuai
//
// Created by XingfuQiu on 15/5/11.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class SearchUserCell: UITableViewCell {
@IBOutlet weak var userAvatar: UIImageView!
@IBOutlet weak var userNick: UILabel!
@IBOutlet weak var userLevel: UILabel!
@IBOutlet weak var userAddr: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.userLevel.backgroundColor = UIColor(hexString: "#FCAA38")
self.userLevel.layer.masksToBounds = true
self.userLevel.layer.cornerRadius = 7
self.userAvatar.layer.masksToBounds = true
self.userAvatar.layer.cornerRadius = 25
self.userAvatar.layer.borderColor = UIColor(hexString: "#000000", alpha: 0.1)!.CGColor
self.userAvatar.layer.borderWidth = 1
//self.username.titleEdgeInsets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 0)
//底部线
var iWidth = UIScreen.mainScreen().bounds.size.width;
var line = UIView(frame: CGRectMake(0, self.frame.size.height-1, iWidth, 1))
line.backgroundColor = UIColor(hexString: "#EFF0F2")
self.addSubview(line)
}
func update(j: JSON) {
// println(j)
self.userAvatar.sd_setImageWithURL(NSURL(string: j["headImg"].stringValue), placeholderImage: DefaultUserAvatar_big!)
self.userNick.text = j["nike"].stringValue
self.userLevel.text = "LV."+j["level"].stringValue
if let address = j["addr"].string {
self.userAddr.setTitle(address, forState: .Normal)
} else {
self.userAddr.setTitle("未定位", forState: .Normal)
}
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.selectionStyle = .None
// Configure the view for the selected state
}
}
|
aed29dee0a7698626ba4ed140c7653de
| 34.537037 | 125 | 0.648775 | false | false | false | false |
Noobish1/KeyedMapper
|
refs/heads/master
|
Example/Pods/Quick/Sources/Quick/Callsite.swift
|
apache-2.0
|
7
|
import Foundation
#if canImport(Darwin)
@objcMembers
public class _CallsiteBase: NSObject {}
#else
public class _CallsiteBase: NSObject {}
#endif
// Ideally we would always use `StaticString` as the type for tracking the file name
// in which an example is defined, for consistency with `assert` etc. from the
// stdlib, and because recent versions of the XCTest overlay require `StaticString`
// when calling `XCTFail`. Under the Objective-C runtime (i.e. building on macOS), we
// have to use `String` instead because StaticString can't be generated from Objective-C
#if SWIFT_PACKAGE
public typealias FileString = StaticString
#else
public typealias FileString = String
#endif
/**
An object encapsulating the file and line number at which
a particular example is defined.
*/
final public class Callsite: _CallsiteBase {
/**
The absolute path of the file in which an example is defined.
*/
public let file: FileString
/**
The line number on which an example is defined.
*/
public let line: UInt
internal init(file: FileString, line: UInt) {
self.file = file
self.line = line
}
}
extension Callsite {
/**
Returns a boolean indicating whether two Callsite objects are equal.
If two callsites are in the same file and on the same line, they must be equal.
*/
@nonobjc public static func == (lhs: Callsite, rhs: Callsite) -> Bool {
return String(describing: lhs.file) == String(describing: rhs.file) && lhs.line == rhs.line
}
}
|
b5b34ed1781e78ce5bee5301d8706e37
| 29.88 | 99 | 0.697539 | false | false | false | false |
Raizlabs/BonMot
|
refs/heads/master
|
Sources/Composable.swift
|
mit
|
1
|
//
// Composable.swift
// BonMot
//
// Created by Brian King on 9/28/16.
// Copyright © 2016 Rightpoint. All rights reserved.
//
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/// Describes types which know how to append themselves to an attributed string.
/// Used to provide a flexible, extensible chaning API for BonMot.
public protocol Composable {
/// Append the receiver to a given attributed string. It is up to the
/// receiver's type to define what it means to be appended to an attributed
/// string. Typically, the receiver will pick up the attributes of the last
/// character of the passed attributed string, but the `baseStyle` parameter
/// can be used to provide additional attributes for the appended string.
///
/// - Parameters:
/// - attributedString: The attributed string to which to append the
/// receiver.
/// - baseStyle: Additional attributes to apply to the receiver before
/// appending it to the passed attributed string.
func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle)
/// Append the receiver to a given attributed string. It is up to the
/// receiver's type to define what it means to be appended to an attributed
/// string. Typically, the receiver will pick up the attributes of the last
/// character of the passed attributed string, but the `baseStyle` parameter
/// can be used to provide additional attributes for the appended string.
///
/// - Parameters:
/// - attributedString: The attributed string to which to append the
/// receiver.
/// - baseStyle: Additional attributes to apply to the receiver before
/// appending it to the passed attributed string.
/// - isLastElement: Whether the receiver is the final element that is
/// being appended to an attributed string. Used in cases
/// where the receiver wants to customize how it is
/// appended if it knows it is the last element, chiefly
/// regarding NSAttributedStringKey.kern.
func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool)
}
extension Composable {
public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle) {
append(to: attributedString, baseStyle: baseStyle, isLastElement: false)
}
/// Create an attributed string with only this composable content, and no
/// base style.
///
/// - returns: a new `NSAttributedString`
public func attributedString() -> NSAttributedString {
return .composed(of: [self])
}
/// Create a new `NSAttributedString` with the style specified.
///
/// - parameter style: The style to use.
/// - parameter overrideParts: The style parts to override on the base style.
/// - parameter stripTrailingKerning: whether to strip NSAttributedStringKey.kern
/// from the last character of the result.
/// - returns: A new `NSAttributedString`.
public func styled(with style: StringStyle, _ overrideParts: StringStyle.Part..., stripTrailingKerning: Bool = true) -> NSAttributedString {
let string = NSMutableAttributedString()
let newStyle = style.byAdding(stringStyle: StringStyle(overrideParts))
append(to: string, baseStyle: newStyle, isLastElement: stripTrailingKerning)
return string
}
/// Create a new `NSAttributedString` with the style parts specified.
///
/// - parameter parts: The style parts to use.
/// - parameter stripTrailingKerning: whether to strip NSAttributedStringKey.kern
/// from the last character of the result.
/// - returns: A new `NSAttributedString`.
public func styled(with parts: StringStyle.Part..., stripTrailingKerning: Bool = true) -> NSAttributedString {
var style = StringStyle()
for part in parts {
style.update(part: part)
}
return styled(with: style, stripTrailingKerning: stripTrailingKerning)
}
}
extension NSAttributedString {
/// Compose an `NSAttributedString` by concatenating every item in
/// `composables` with `baseStyle` applied. The `separator` is inserted
/// between every item. `baseStyle` acts as the default style, and apply to
/// the `Composable` item only if the `Composable` does not have a style
/// value configured.
///
/// - parameter composables: An array of `Composable` to join into an
/// `NSAttributedString`.
/// - parameter baseStyle: The base style to apply to every `Composable`.
/// If no `baseStyle` is supplied, no additional
/// styling will be added.
/// - parameter separator: The separator to insert between every pair of
/// elements in `composables`.
/// - returns: A new `NSAttributedString`.
@nonobjc public static func composed(of composables: [Composable], baseStyle: StringStyle = StringStyle(), separator: Composable? = nil) -> NSAttributedString {
let string = NSMutableAttributedString()
string.beginEditing()
let lastComposableIndex = composables.endIndex
for (index, composable) in composables.enumerated() {
composable.append(to: string, baseStyle: baseStyle, isLastElement: index == lastComposableIndex - 1)
if let separator = separator {
if index != composables.indices.last {
separator.append(to: string, baseStyle: baseStyle)
}
}
}
string.endEditing()
return string
}
public func styled(with style: StringStyle, _ overrideParts: StringStyle.Part...) -> NSAttributedString {
let newStyle = style.byAdding(overrideParts)
let newAttributes = newStyle.attributes
let mutableSelf = mutableStringCopy()
let fullRange = NSRange(location: 0, length: mutableSelf.string.utf16.count)
for (key, value) in newAttributes {
mutableSelf.addAttribute(key, value: value, range: fullRange)
}
return mutableSelf.immutableCopy()
}
}
extension NSAttributedString: Composable {
/// Append this `NSAttributedString` to `attributedString`, with `baseStyle`
/// applied as default values. This method enumerates all attribute ranges
/// in the receiver and use `baseStyle` to supply defaults for the attributes.
/// This effectively merges `baseStyle` and the embedded attributes, with a
/// tie going to the embedded attributes.
///
/// See `StringStyle.supplyDefaults(for:)` for more details.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The `StringStyle` that is overridden by the
/// receiver's attributes
@nonobjc public final func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
let range = NSRange(location: 0, length: length)
enumerateAttributes(in: range, options: []) { (attributes, range, _) in
let substring = self.attributedSubstring(from: range)
// Add the string with the defaults supplied by the style
let newString = baseStyle.attributedString(from: substring.string, existingAttributes: attributes)
attributedString.append(newString)
}
if isLastElement {
attributedString.removeKerningFromLastCharacter()
}
else {
attributedString.restoreKerningOnLastCharacter()
}
}
}
extension String: Composable {
/// Append the receiver to `attributedString`, with `baseStyle` applied as
/// default values. Since `String` has no style, `baseStyle` is the only
/// style that is used.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The style to use for this string.
public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
attributedString.append(baseStyle.attributedString(from: self))
if isLastElement {
attributedString.removeKerningFromLastCharacter()
}
else {
attributedString.restoreKerningOnLastCharacter()
}
}
}
#if os(iOS) || os(tvOS) || os(OSX)
extension BONImage: Composable {
/// Append the receiver to `attributedString`, with `baseStyle` applied as
/// default values. Only a few properties in `baseStyle` are relevant when
/// styling images. These include `baselineOffset`, as well as `color` for
/// template images. All attributes are stored in the range of the image for
/// consistency inside the attributed string.
///
/// - note: the `NSBaselineOffsetAttributeName` value is used as the
/// `bounds.origin.y` value for the text attachment, and is removed from the
/// attributes dictionary to fix an issue with UIKit.
///
/// - note: `NSTextAttachment` is not available on watchOS.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The style to use.
@nonobjc public final func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
let baselinesOffsetForAttachment = baseStyle.baselineOffset ?? 0
let attachment = NSTextAttachment()
#if os(OSX)
let imageIsTemplate = isTemplate
#else
let imageIsTemplate = (renderingMode != .alwaysOriginal)
#endif
var imageToUse = self
if let color = baseStyle.color {
if imageIsTemplate {
imageToUse = tintedImage(color: color)
}
}
attachment.image = imageToUse
attachment.bounds = CGRect(origin: CGPoint(x: 0, y: baselinesOffsetForAttachment), size: size)
let attachmentString = NSAttributedString(attachment: attachment).mutableStringCopy()
// Remove the baseline offset from the attributes so it isn't applied twice
var attributes = baseStyle.attributes
attributes[.baselineOffset] = nil
attachmentString.addAttributes(attributes, range: NSRange(location: 0, length: attachmentString.length))
attributedString.append(attachmentString)
}
}
#endif
extension Special: Composable {
/// Append the receiver's string value to `attributedString`, with `baseStyle`
/// applied as default values.
///
/// - parameter to: The attributed string to which to append the receiver.
/// - parameter baseStyle: The style to use.
public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) {
description.append(to: attributedString, baseStyle: baseStyle)
}
}
public extension Sequence where Element: Composable {
func joined(separator: Composable = "") -> NSAttributedString {
return NSAttributedString.composed(of: Array(self), separator: separator)
}
}
extension NSAttributedString.Key {
public static let bonMotRemovedKernAttribute = NSAttributedString.Key("com.raizlabs.bonmot.removedKernAttributeRemoved")
}
extension NSMutableAttributedString {
func removeKerningFromLastCharacter() {
guard length != 0 else {
return
}
let lastCharacterLength = string.suffix(1).utf16.count
let lastCharacterRange = NSRange(location: length - lastCharacterLength, length: lastCharacterLength)
guard let currentKernValue = attribute(.kern, at: lastCharacterRange.location, effectiveRange: nil) else {
return
}
removeAttribute(.kern, range: lastCharacterRange)
addAttribute(.bonMotRemovedKernAttribute, value: currentKernValue, range: lastCharacterRange)
}
func restoreKerningOnLastCharacter() {
guard length != 0 else {
return
}
let lastCharacterLength = string.suffix(1).utf16.count
let lastCharacterRange = NSRange(location: length - lastCharacterLength, length: lastCharacterLength)
guard let currentKernValue = attribute(.bonMotRemovedKernAttribute, at: lastCharacterRange.location, effectiveRange: nil) else {
return
}
removeAttribute(.bonMotRemovedKernAttribute, range: lastCharacterRange)
addAttribute(.kern, value: currentKernValue, range: lastCharacterRange)
}
}
|
465a211dea2fb7bae8301803c89c1aeb
| 41.052459 | 164 | 0.665523 | false | false | false | false |
wikimedia/wikipedia-ios
|
refs/heads/main
|
Wikipedia/Code/CollectionViewCell.swift
|
mit
|
1
|
import UIKit
// CollectionViewCell is the base class of collection view cells that use manual layout.
// These cells use a manual layout rather than auto layout for a few reasons:
// 1. A significant in-code implementation was required anyway for handling the complexity of
// hiding & showing different parts of the cells with auto layout
// 2. The performance advantage over auto layout for views that contain several article cells.
// (To further alleviate this performance issue, ColumnarCollectionViewLayout could be updated
// to not require a full layout pass for calculating the total collection view content size. Instead,
// it could do a rough estimate pass, and then update the content size as the user scrolls.)
// 3. Handling RTL content on LTR devices and vice versa
open class CollectionViewCell: UICollectionViewCell {
// MARK: - Methods for subclassing
// Subclassers should override setup instead of any of the initializers. Subclassers must call super.setup()
open func setup() {
contentView.translatesAutoresizingMaskIntoConstraints = false
preservesSuperviewLayoutMargins = false
contentView.preservesSuperviewLayoutMargins = false
insetsLayoutMarginsFromSafeArea = false
contentView.insetsLayoutMarginsFromSafeArea = false
autoresizesSubviews = false
contentView.autoresizesSubviews = false
backgroundView = UIView()
selectedBackgroundView = UIView()
reset()
setNeedsLayout()
}
open func reset() {
}
public var labelBackgroundColor: UIColor? {
didSet {
updateBackgroundColorOfLabels()
}
}
public func setBackgroundColors(_ deselected: UIColor, selected: UIColor) {
backgroundView?.backgroundColor = deselected
selectedBackgroundView?.backgroundColor = selected
let newColor = isSelectedOrHighlighted ? selected : deselected
if newColor != labelBackgroundColor {
labelBackgroundColor = newColor
}
}
// Subclassers should call super
open func updateBackgroundColorOfLabels() {
}
var isSelectedOrHighlighted: Bool = false
public func updateSelectedOrHighlighted() {
let newIsSelectedOrHighlighted = isSelected || isHighlighted
guard newIsSelectedOrHighlighted != isSelectedOrHighlighted else {
return
}
isSelectedOrHighlighted = newIsSelectedOrHighlighted
// It appears that background color changes aren't properly animated when set within the animation block around isHighlighted/isSelected state changes
// https://phabricator.wikimedia.org/T174341
// To work around this, first set the background to clear without animation so that it stays clear throughought the animation
UIView.performWithoutAnimation {
self.labelBackgroundColor = .clear
}
// Then update the completion block to set the actual opaque color we want after the animation completes
let existingCompletionBlock = CATransaction.completionBlock()
CATransaction.setCompletionBlock {
if let block = existingCompletionBlock {
block()
}
self.labelBackgroundColor = self.isSelected || self.isHighlighted ? self.selectedBackgroundView?.backgroundColor : self.backgroundView?.backgroundColor
}
}
open override var isHighlighted: Bool {
didSet {
updateSelectedOrHighlighted()
}
}
open override var isSelected: Bool {
didSet {
updateSelectedOrHighlighted()
}
}
// Subclassers should override sizeThatFits:apply: instead of layoutSubviews to lay out subviews.
// In this method, subclassers should calculate the appropriate layout size and if apply is `true`,
// apply the layout to the subviews.
open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
return size
}
// Subclassers should override updateAccessibilityElements to update any accessibility elements
// that should be updated after layout. Subclassers must call super.updateAccessibilityElements()
open func updateAccessibilityElements() {
}
// MARK: - Initializers
// Don't override these initializers, use setup() instead
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: - Cell lifecycle
open override func prepareForReuse() {
super.prepareForReuse()
reset()
}
// MARK: - Layout
open override func layoutMarginsDidChange() {
super.layoutMarginsDidChange()
setNeedsLayout()
}
final override public func layoutSubviews() {
super.layoutSubviews()
contentView.frame = bounds
backgroundView?.frame = bounds
selectedBackgroundView?.frame = bounds
let size = bounds.size
_ = sizeThatFits(size, apply: true)
updateAccessibilityElements()
#if DEBUG
for view in subviews {
guard view !== backgroundView, view !== selectedBackgroundView else {
continue
}
assert(view.autoresizingMask == [])
assert(view.constraints == [])
}
#endif
}
final override public func sizeThatFits(_ size: CGSize) -> CGSize {
return sizeThatFits(size, apply: false)
}
final override public func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
if let attributesToFit = layoutAttributes as? ColumnarCollectionViewLayoutAttributes {
layoutMargins = attributesToFit.layoutMargins
if attributesToFit.precalculated {
return attributesToFit
}
}
var sizeToFit = layoutAttributes.size
sizeToFit.height = UIView.noIntrinsicMetric
var fitSize = self.sizeThatFits(sizeToFit)
if fitSize == sizeToFit {
return layoutAttributes
} else if let attributes = layoutAttributes.copy() as? UICollectionViewLayoutAttributes {
fitSize.width = sizeToFit.width
if fitSize.height == CGFloat.greatestFiniteMagnitude || fitSize.height == UIView.noIntrinsicMetric {
fitSize.height = layoutAttributes.size.height
}
attributes.frame = CGRect(origin: layoutAttributes.frame.origin, size: fitSize)
return attributes
} else {
return layoutAttributes
}
}
// MARK: - Dynamic Type
// Only applies new fonts if the content size category changes
open override func setNeedsLayout() {
maybeUpdateFonts(with: traitCollection)
super.setNeedsLayout()
}
override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setNeedsLayout()
}
var contentSizeCategory: UIContentSizeCategory?
fileprivate func maybeUpdateFonts(with traitCollection: UITraitCollection) {
guard contentSizeCategory == nil || contentSizeCategory != traitCollection.wmf_preferredContentSizeCategory else {
return
}
contentSizeCategory = traitCollection.wmf_preferredContentSizeCategory
updateFonts(with: traitCollection)
}
// Override this method and call super
open func updateFonts(with traitCollection: UITraitCollection) {
}
// MARK: - Layout Margins
public var layoutMarginsAdditions: UIEdgeInsets = .zero
public var layoutMarginsInteractiveAdditions: UIEdgeInsets = .zero
public func layoutWidth(for size: CGSize) -> CGFloat { // layoutWidth doesn't take into account interactive additions
return size.width - layoutMargins.left - layoutMargins.right - layoutMarginsAdditions.right - layoutMarginsAdditions.left
}
public var calculatedLayoutMargins: UIEdgeInsets {
let margins = self.layoutMargins
return UIEdgeInsets(top: margins.top + layoutMarginsAdditions.top + layoutMarginsInteractiveAdditions.top,
left: margins.left + layoutMarginsAdditions.left + layoutMarginsInteractiveAdditions.left,
bottom: margins.bottom + layoutMarginsAdditions.bottom + layoutMarginsInteractiveAdditions.bottom,
right: margins.right + layoutMarginsAdditions.right + layoutMarginsInteractiveAdditions.right)
}
}
|
000d34a742f5deb53125f83197174a75
| 38.408889 | 164 | 0.672268 | false | false | false | false |
A752575700/HOMEWORK
|
refs/heads/master
|
Day4_2/MyPlayground.playground/Contents.swift
|
mit
|
1
|
public class Stack {
//must initialize
var items: [Int] = []
public func push(number: Int){
self.items.append(number)
}
//?是声明时候用 !是调用时候用
var top : Int? {
println(items.last)
return items.last
}
//could be EMPTY
public func pop() -> Int? {
if items.count > 0 {
var toptop = self.top
println(toptop)
self.items.removeLast()
return toptop
}else {
return nil
}
}
}
var Stack1 = Stack()
Stack1.push(8)
Stack1.push(11)
Stack1.push(92)
println(Stack1.top)
println(Stack1.pop()!)
Stack1.pop()
Stack1.pop()
Stack1.pop()
println()
//////////////////////////////////////////////////////////////////////
public class Queue {
var items: [Int] = []
public func enqueue(number: Int){
self.items.append(number)
}
public func dequeue()->Int?{
var first=items[0]
self.items.removeAtIndex(0)
return first
}
public func description()->String?{
var outcome: String = " "
for (var i=0; i < self.items.count;i++){
var number = dequeue()!
outcome = outcome + "\(number)"
enqueue(number)
}
println(outcome)
return outcome
}
public func isEmpty()->Bool{
if description() == " "{
return true
}
return false
}
}
var Queue1 = Queue()
Queue1.enqueue(6)
Queue1.enqueue(7)
Queue1.enqueue(8)
Queue1.description()
println(Queue1.dequeue())
Queue1.description()
println(Queue1.isEmpty())
//print先执行
//////////////////////////////////////////////////////////////////////
//<T:..>用的时候再声明类型
public class Node <T:Equatable>{
//变量有赋值时可以不用initializer
var value: T
var next: Node? = nil
/*
public func addValue(x: Int){
self.value = x
}*/
//类里面有value就需要下划线
init (_ value: T){
self.value = value
}
}
public class List<T:Equatable>{
var head: Node<T>? = nil
public func addTail(newvalue: T){
if head == nil{
head = Node(newvalue)
}
else {
var lastnode = head
while lastnode?.next != nil {
lastnode = lastnode?.next
}
lastnode?.next = Node(newvalue)
}
}
public func addHead(newvalue: T){
if head == nil{
head = Node(newvalue)
}
else{
var newhead = Node(newvalue)
newhead.next = head
head = newhead
}
}
public func description() -> String?{
var outcome: String = "\(head!.value)"
var item = head
while item?.next != nil{
item = item!.next
outcome = outcome + " \(item!.value)"
}
return outcome
}
public func removeFirstValue(value: T){
var item = head
var isFound = false
if item!.value == value {
if item!.next == nil{
head = nil
}
else if item!.next != nil{
head = item?.next
}
}
else {
//while item!.next != nil{
var item2 = item
while item2!.next != nil{
item = item2
item2 = item2!.next
//println(item2!.value)
if(item2!.value == value){
isFound = true
break
}
}
if isFound == true {
item!.next = item2!.next
}else{
println("\(value) not found")
}
}
}
}
var newList = List<Int>()
newList.addTail(5)
newList.addTail(6)
newList.addHead(7)
println(newList.description()!)
newList.removeFirstValue(5)
println(newList.description()!)
newList.removeFirstValue(5)
println(newList.description()!)
var newListS = List<String>()
newListS.addTail("Tommy")
newListS.addTail("Rocky")
newListS.addTail("Evan")
println(newListS.description()!)
newListS.removeFirstValue("Rocky")
println(newListS.description()!)
|
65c44e59a1ffc603aedfee228d00d461
| 19.580488 | 70 | 0.484238 | false | false | false | false |
lexchou/swallow
|
refs/heads/master
|
stdlib/core/OperatorOr.swift
|
bsd-3-clause
|
1
|
func |(lhs: Int, rhs: Int) -> Int {
return 0//TODO
}
func |(lhs: UInt, rhs: UInt) -> UInt {
return 0//TODO
}
func |(lhs: Int64, rhs: Int64) -> Int64 {
return 0//TODO
}
func |(lhs: UInt64, rhs: UInt64) -> UInt64 {
return 0//TODO
}
func |(lhs: Int32, rhs: Int32) -> Int32 {
return 0//TODO
}
func |(lhs: UInt32, rhs: UInt32) -> UInt32 {
return 0//TODO
}
func |(lhs: Int16, rhs: Int16) -> Int16 {
return 0//TODO
}
func |(lhs: UInt16, rhs: UInt16) -> UInt16 {
return 0//TODO
}
func |(lhs: Int8, rhs: Int8) -> Int8 {
return 0//TODO
}
func |(lhs: UInt8, rhs: UInt8) -> UInt8 {
return 0//TODO
}
func |<T : _RawOptionSetType>(a: T, b: T) -> T {
return 0//TODO
}
func |(lhs: Bool, rhs: Bool) -> Bool {
return 0//TODO
}
func |=(inout lhs: Int16, rhs: Int16) {
return 0//TODO
}
func |=(inout lhs: UInt32, rhs: UInt32) {
return 0//TODO
}
func |=(inout lhs: Int32, rhs: Int32) {
return 0//TODO
}
func |=(inout lhs: UInt64, rhs: UInt64) {
return 0//TODO
}
func |=(inout lhs: Int64, rhs: Int64) {
return 0//TODO
}
func |=(inout lhs: UInt, rhs: UInt) {
return 0//TODO
}
func |=(inout lhs: Int, rhs: Int) {
return 0//TODO
}
func |=<T : BitwiseOperationsType>(inout lhs: T, rhs: T) {
return 0//TODO
}
func |=(inout lhs: UInt16, rhs: UInt16) {
return 0//TODO
}
func |=(inout lhs: Bool, rhs: Bool) {
return 0//TODO
}
func |=(inout lhs: UInt8, rhs: UInt8) {
return 0//TODO
}
func |=(inout lhs: Int8, rhs: Int8) {
return 0//TODO
}
/// If `lhs` is `true`, return it. Otherwise, evaluate `rhs` and
/// return its `boolValue`.
@inline(__always) func ||<T : BooleanType, U : BooleanType>(lhs: T, rhs: @autoclosure () -> U) -> Bool {
return 0//TODO
}
func ||<T : BooleanType>(lhs: T, rhs: @autoclosure () -> Bool) -> Bool {
return 0//TODO
}
|
6eb62f802745500bea0c0b91b856974b
| 16.242991 | 104 | 0.572358 | false | false | false | false |
wikimedia/wikipedia-ios
|
refs/heads/main
|
Wikipedia/Code/NotificationsCenterCell.swift
|
mit
|
1
|
import UIKit
protocol NotificationsCenterCellDelegate: AnyObject {
func userDidTapMarkAsReadUnreadActionForCell(_ cell: NotificationsCenterCell)
func userDidTapMoreActionForCell(_ cell: NotificationsCenterCell)
}
final class NotificationsCenterCell: UICollectionViewCell {
// MARK: - Properties
static let reuseIdentifier = "NotificationsCenterCell"
static let swipeEdgeBuffer: CGFloat = 20
fileprivate var theme: Theme = .light
fileprivate(set) var viewModel: NotificationsCenterCellViewModel?
weak var delegate: NotificationsCenterCellDelegate?
// MARK: - UI Elements
lazy var leadingImageView: RoundedImageView = {
let view = RoundedImageView()
view.translatesAutoresizingMaskIntoConstraints = false
view.imageView.contentMode = .scaleAspectFit
view.layer.borderWidth = 2
view.layer.borderColor = UIColor.clear.cgColor
return view
}()
lazy var projectSourceLabel: InsetLabelView = {
let insetLabel = InsetLabelView()
insetLabel.translatesAutoresizingMaskIntoConstraints = false
insetLabel.label.setContentCompressionResistancePriority(.required, for: .vertical)
insetLabel.label.font = UIFont.wmf_font(.caption1, compatibleWithTraitCollection: traitCollection)
insetLabel.label.adjustsFontForContentSizeCategory = true
insetLabel.label.numberOfLines = 1
insetLabel.label.text = "EN"
insetLabel.label.textAlignment = .center
insetLabel.layer.cornerRadius = 3
insetLabel.layer.borderWidth = 1
insetLabel.layer.borderColor = UIColor.black.cgColor
insetLabel.insets = NSDirectionalEdgeInsets(top: 4, leading: 4, bottom: -4, trailing: -4)
insetLabel.isHidden = true
return insetLabel
}()
lazy var projectSourceImage: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "wikimedia-project-commons")
imageView.contentMode = .scaleAspectFit
imageView.isHidden = true
return imageView
}()
lazy var headerLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.font = UIFont.wmf_font(.headline, compatibleWithTraitCollection: traitCollection)
label.adjustsFontForContentSizeCategory = true
label.textAlignment = effectiveUserInterfaceLayoutDirection == .rightToLeft ? .right : .left
label.numberOfLines = 1
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
label.setContentHuggingPriority(.defaultLow, for: .horizontal)
label.text = ""
label.isUserInteractionEnabled = true
return label
}()
lazy var subheaderLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
label.adjustsFontForContentSizeCategory = true
label.numberOfLines = 1
label.textAlignment = effectiveUserInterfaceLayoutDirection == .rightToLeft ? .right : .left
label.text = ""
return label
}()
lazy var messageSummaryLabel: UITextView = {
let label = UITextView()
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.setContentHuggingPriority(.defaultLow, for: .vertical)
label.font = UIFont.wmf_font(.body, compatibleWithTraitCollection: traitCollection)
label.adjustsFontForContentSizeCategory = true
label.textContainer.lineBreakMode = .byTruncatingTail
label.textAlignment = effectiveUserInterfaceLayoutDirection == .rightToLeft ? .right : .left
label.textContainer.maximumNumberOfLines = 3
label.text = ""
label.isScrollEnabled = false
label.isEditable = false
label.isSelectable = false
label.textContainerInset = .zero
label.textContainer.lineFragmentPadding = 0
label.isUserInteractionEnabled = false
label.backgroundColor = .clear
return label
}()
lazy var relativeTimeAgoLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.font = UIFont.wmf_font(.boldFootnote, compatibleWithTraitCollection: traitCollection)
label.adjustsFontForContentSizeCategory = true
label.numberOfLines = 1
label.textAlignment = effectiveUserInterfaceLayoutDirection == .rightToLeft ? .left : .right
label.text = ""
return label
}()
lazy var metaLabel: UILabel = {
let label = UILabel()
label.font = UIFont.wmf_font(.mediumFootnote, compatibleWithTraitCollection: traitCollection)
label.adjustsFontForContentSizeCategory = true
label.setContentCompressionResistancePriority(.required, for: .vertical)
return label
}()
lazy var metaImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.adjustsImageSizeForAccessibilityContentSizeCategory = true
imageView.setContentCompressionResistancePriority(.required, for: .vertical)
imageView.contentMode = .scaleAspectFit
return imageView
}()
lazy var swipeMoreActionButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(tappedMoreAction), for: .primaryActionTriggered)
return button
}()
lazy var swipeMarkAsReadUnreadActionButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(tappedReadUnreadAction), for: .primaryActionTriggered)
return button
}()
// MARK: - UI Elements - Stacks
lazy var mainVerticalStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
return stackView
}()
lazy var internalHorizontalStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fill
return stackView
}()
lazy var internalVerticalNotificationContentStack: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
return stackView
}()
lazy var metaStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
lazy var swipeActionButtonStack: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.alignment = .center
return stackView
}()
lazy var swipeMoreStack: StackedImageLabelView = {
let stack = StackedImageLabelView()
stack.translatesAutoresizingMaskIntoConstraints = false
let configuration = UIImage.SymbolConfiguration(weight: .semibold)
stack.imageView.image = UIImage(systemName: "ellipsis.circle.fill", withConfiguration: configuration)
stack.backgroundColor = .base30
stack.increaseLabelTopPadding = true
return stack
}()
lazy var swipeReadUnreadStack: StackedImageLabelView = {
let stack = StackedImageLabelView()
stack.translatesAutoresizingMaskIntoConstraints = false
let configuration = UIImage.SymbolConfiguration(weight: .semibold)
stack.imageView.image = UIImage(systemName: "envelope", withConfiguration: configuration)
stack.backgroundColor = .green50
return stack
}()
var swipeBackgroundFillView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .base30
return view
}()
// MARK: - UI Elements - Containers
lazy var foregroundContentContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var backgroundActionsContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.isUserInteractionEnabled = true
return view
}()
lazy var leadingContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var projectSourceContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var headerTextContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var swipeMoreActionContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .base30
view.isUserInteractionEnabled = true
return view
}()
lazy var swipeMarkAsReadUnreadActionContainer: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .green50
view.isUserInteractionEnabled = true
return view
}()
// MARK: - UI Elements - Helpers
lazy var cellSeparator: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func prepareForReuse() {
super.prepareForReuse()
self.viewModel = nil
self.foregroundContentContainer.transform = .identity
}
override var isHighlighted: Bool {
didSet {
foregroundContentContainer.backgroundColor = isHighlighted ? theme.colors.batchSelectionBackground : theme.colors.paperBackground
}
}
override var isSelected: Bool {
didSet {
foregroundContentContainer.backgroundColor = isSelected ? theme.colors.batchSelectionBackground : theme.colors.paperBackground
}
}
func setup() {
let topMargin: CGFloat = 13
let edgeMargin: CGFloat = 11
selectedBackgroundView = nil
foregroundContentContainer.addSubview(leadingContainer)
foregroundContentContainer.addSubview(mainVerticalStackView)
backgroundActionsContainer.addSubview(swipeActionButtonStack)
leadingContainer.addSubview(leadingImageView)
headerTextContainer.addSubview(headerLabel)
headerTextContainer.addSubview(relativeTimeAgoLabel)
mainVerticalStackView.addArrangedSubview(headerTextContainer)
mainVerticalStackView.addArrangedSubview(internalHorizontalStackView)
internalHorizontalStackView.addArrangedSubview(internalVerticalNotificationContentStack)
internalHorizontalStackView.addArrangedSubview(projectSourceContainer)
metaStackView.addArrangedSubview(metaImageView)
metaStackView.addArrangedSubview(HorizontalSpacerView.spacerWith(space: 3))
metaStackView.addArrangedSubview(metaLabel)
projectSourceContainer.addSubview(projectSourceLabel)
projectSourceContainer.addSubview(projectSourceImage)
let minimumSummaryHeight = (traitCollection.horizontalSizeClass == .regular) ? 40.0 : 64.0
internalVerticalNotificationContentStack.addArrangedSubview(VerticalSpacerView.spacerWith(space: 6))
internalVerticalNotificationContentStack.addArrangedSubview(subheaderLabel)
internalVerticalNotificationContentStack.addArrangedSubview(VerticalSpacerView.spacerWith(space: 6))
internalVerticalNotificationContentStack.addArrangedSubview(messageSummaryLabel)
NSLayoutConstraint.activate([
messageSummaryLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: minimumSummaryHeight)
])
internalVerticalNotificationContentStack.addArrangedSubview(VerticalSpacerView.spacerWith(space: 3))
internalVerticalNotificationContentStack.addArrangedSubview(metaStackView)
internalVerticalNotificationContentStack.addArrangedSubview(VerticalSpacerView.spacerWith(space: 3))
contentView.addSubview(swipeBackgroundFillView)
contentView.addSubview(backgroundActionsContainer)
contentView.addSubview(foregroundContentContainer)
contentView.addSubview(cellSeparator)
// Foreground and Background Container Constraints
NSLayoutConstraint.activate([
swipeBackgroundFillView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: NotificationsCenterCell.swipeEdgeBuffer * 2.0),
swipeBackgroundFillView.topAnchor.constraint(equalTo: contentView.topAnchor),
swipeBackgroundFillView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
swipeBackgroundFillView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
backgroundActionsContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
backgroundActionsContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
backgroundActionsContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
backgroundActionsContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
foregroundContentContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
foregroundContentContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
foregroundContentContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
foregroundContentContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
// Primary Hierarchy Constraints
NSLayoutConstraint.activate([
leadingContainer.leadingAnchor.constraint(equalTo: contentView.readableContentGuide.leadingAnchor),
leadingContainer.topAnchor.constraint(equalTo: mainVerticalStackView.topAnchor),
leadingContainer.bottomAnchor.constraint(equalTo: foregroundContentContainer.bottomAnchor),
leadingContainer.trailingAnchor.constraint(equalTo: mainVerticalStackView.leadingAnchor),
mainVerticalStackView.topAnchor.constraint(equalTo: foregroundContentContainer.topAnchor, constant: topMargin),
mainVerticalStackView.bottomAnchor.constraint(equalTo: foregroundContentContainer.bottomAnchor, constant: -edgeMargin),
mainVerticalStackView.trailingAnchor.constraint(equalTo: contentView.readableContentGuide.trailingAnchor),
headerTextContainer.trailingAnchor.constraint(equalTo: contentView.readableContentGuide.trailingAnchor, constant: -edgeMargin),
cellSeparator.heightAnchor.constraint(equalToConstant: 0.5),
cellSeparator.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
cellSeparator.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
cellSeparator.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)
])
// Leading Image Constraints
NSLayoutConstraint.activate([
leadingImageView.heightAnchor.constraint(equalToConstant: 32),
leadingImageView.widthAnchor.constraint(equalToConstant: 32),
leadingImageView.leadingAnchor.constraint(equalTo: leadingContainer.leadingAnchor, constant: edgeMargin),
leadingImageView.trailingAnchor.constraint(equalTo: leadingContainer.trailingAnchor, constant: -edgeMargin),
leadingImageView.centerYAnchor.constraint(equalTo: headerLabel.centerYAnchor, constant: topMargin/3)
])
// Header label constraints
NSLayoutConstraint.activate([
headerLabel.leadingAnchor.constraint(equalTo: headerTextContainer.leadingAnchor),
headerLabel.topAnchor.constraint(equalTo: headerTextContainer.topAnchor),
headerLabel.bottomAnchor.constraint(equalTo: headerTextContainer.bottomAnchor),
headerLabel.trailingAnchor.constraint(equalTo: relativeTimeAgoLabel.leadingAnchor),
headerLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 50),
relativeTimeAgoLabel.topAnchor.constraint(equalTo: headerTextContainer.topAnchor),
relativeTimeAgoLabel.bottomAnchor.constraint(equalTo: headerTextContainer.bottomAnchor),
relativeTimeAgoLabel.trailingAnchor.constraint(equalTo: headerTextContainer.trailingAnchor)
])
// Project Source
NSLayoutConstraint.activate([
projectSourceContainer.widthAnchor.constraint(equalToConstant: 50),
projectSourceContainer.trailingAnchor.constraint(equalTo: contentView.readableContentGuide.trailingAnchor, constant: -edgeMargin),
projectSourceLabel.topAnchor.constraint(equalTo: subheaderLabel.topAnchor),
projectSourceLabel.trailingAnchor.constraint(equalTo: projectSourceContainer.trailingAnchor),
projectSourceImage.topAnchor.constraint(equalTo: subheaderLabel.topAnchor),
projectSourceImage.trailingAnchor.constraint(equalTo: projectSourceContainer.trailingAnchor)
])
// Meta Content
NSLayoutConstraint.activate([
metaImageView.widthAnchor.constraint(equalTo: metaImageView.heightAnchor)
])
// Swipe Actions
swipeActionButtonStack.addArrangedSubview(swipeMoreStack)
swipeActionButtonStack.addArrangedSubview(swipeReadUnreadStack)
swipeMoreStack.addSubview(swipeMoreActionButton)
swipeReadUnreadStack.addSubview(swipeMarkAsReadUnreadActionButton)
NSLayoutConstraint.activate([
swipeActionButtonStack.topAnchor.constraint(equalTo: backgroundActionsContainer.topAnchor),
swipeActionButtonStack.bottomAnchor.constraint(equalTo: backgroundActionsContainer.bottomAnchor),
swipeActionButtonStack.trailingAnchor.constraint(equalTo: backgroundActionsContainer.trailingAnchor),
swipeActionButtonStack.widthAnchor.constraint(equalToConstant: 200),
swipeMoreActionButton.topAnchor.constraint(equalTo: swipeMoreStack.topAnchor),
swipeMoreActionButton.bottomAnchor.constraint(equalTo: swipeMoreStack.bottomAnchor),
swipeMoreActionButton.leadingAnchor.constraint(equalTo: swipeMoreStack.leadingAnchor),
swipeMoreActionButton.trailingAnchor.constraint(equalTo: swipeMoreStack.trailingAnchor),
swipeMarkAsReadUnreadActionButton.topAnchor.constraint(equalTo: swipeReadUnreadStack.topAnchor),
swipeMarkAsReadUnreadActionButton.bottomAnchor.constraint(equalTo: swipeReadUnreadStack.bottomAnchor),
swipeMarkAsReadUnreadActionButton.leadingAnchor.constraint(equalTo: swipeReadUnreadStack.leadingAnchor),
swipeMarkAsReadUnreadActionButton.trailingAnchor.constraint(equalTo: swipeReadUnreadStack.trailingAnchor),
swipeMoreStack.heightAnchor.constraint(equalTo: contentView.heightAnchor),
swipeReadUnreadStack.heightAnchor.constraint(equalTo: contentView.heightAnchor)
])
}
// MARK: - Public
fileprivate func setupAccessibility(_ viewModel: NotificationsCenterCellViewModel) {
accessibilityLabel = viewModel.accessibilityText
isAccessibilityElement = true
if !viewModel.displayState.isEditing {
let moreActionAccessibilityLabel = WMFLocalizedString("notifications-center-more-action-accessibility-label", value: "More", comment: "Acessibility label for the More custom action")
let moreActionAccessibilityActionLabel = viewModel.isRead ? CommonStrings.notificationsCenterMarkAsUnread : CommonStrings.notificationsCenterMarkAsRead
let moreAction = UIAccessibilityCustomAction(name: moreActionAccessibilityLabel, target: self, selector: #selector(tappedMoreAction))
let markasReadorUnreadAction = UIAccessibilityCustomAction(name: moreActionAccessibilityActionLabel, target: self, selector: #selector(tappedReadUnreadAction))
accessibilityCustomActions = [moreAction, markasReadorUnreadAction]
} else {
accessibilityCustomActions = nil
}
}
func configure(viewModel: NotificationsCenterCellViewModel, theme: Theme) {
self.viewModel = viewModel
self.theme = theme
updateCellStyle(forDisplayState: viewModel.displayState)
updateLabels(forViewModel: viewModel)
updateProject(forViewModel: viewModel)
updateMetaContent(forViewModel: viewModel)
setupAccessibility(viewModel)
}
func configure(theme: Theme) {
guard let viewModel = viewModel else {
return
}
configure(viewModel: viewModel, theme: theme)
}
}
// MARK: - Private
private extension NotificationsCenterCell {
func updateColors(forDisplayState displayState: NotificationsCenterCellDisplayState) {
guard let notificationType = viewModel?.notificationType else {
return
}
let cellStyle = NotificationsCenterCellStyle(theme: theme, traitCollection: traitCollection, notificationType: notificationType)
// Colors
foregroundContentContainer.backgroundColor = isHighlighted || isSelected || displayState.isSelected ? theme.colors.batchSelectionBackground : theme.colors.paperBackground
cellSeparator.backgroundColor = cellStyle.cellSeparatorColor
let textColor = cellStyle.textColor(displayState)
headerLabel.textColor = textColor
subheaderLabel.textColor = textColor
messageSummaryLabel.textColor = textColor
relativeTimeAgoLabel.textColor = textColor
metaImageView.tintColor = textColor
metaLabel.textColor = textColor
projectSourceLabel.label.textColor = textColor
projectSourceLabel.layer.borderColor = textColor.cgColor
projectSourceImage.tintColor = textColor
}
func updateCellStyle(forDisplayState displayState: NotificationsCenterCellDisplayState) {
guard let notificationType = viewModel?.notificationType else {
return
}
let cellStyle = NotificationsCenterCellStyle(theme: theme, traitCollection: traitCollection, notificationType: notificationType)
updateColors(forDisplayState: displayState)
// Fonts
headerLabel.font = cellStyle.headerFont(displayState)
subheaderLabel.font = cellStyle.subheaderFont(displayState)
messageSummaryLabel.font = cellStyle.messageFont
relativeTimeAgoLabel.font = cellStyle.relativeTimeAgoFont(displayState)
metaLabel.font = cellStyle.metadataFont(displayState)
projectSourceLabel.label.font = cellStyle.projectSourceFont
// Image
leadingImageView.backgroundColor = cellStyle.leadingImageBackgroundColor(displayState)
leadingImageView.imageView.image = cellStyle.leadingImage(displayState)
leadingImageView.imageView.tintColor = cellStyle.leadingImageTintColor
leadingImageView.layer.borderColor = cellStyle.leadingImageBorderColor(displayState).cgColor
}
func updateLabels(forViewModel viewModel: NotificationsCenterCellViewModel) {
headerLabel.text = viewModel.headerText
subheaderLabel.text = viewModel.subheaderText
let messageSummaryText = viewModel.bodyText ?? ""
messageSummaryLabel.text = messageSummaryText.isEmpty ? " " : viewModel.bodyText
let trimmedSummary = messageSummaryLabel.text.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)
messageSummaryLabel.text = trimmedSummary
relativeTimeAgoLabel.text = viewModel.dateText
swipeMoreStack.label.text = WMFLocalizedString("notifications-center-swipe-more", value: "More", comment: "Button text for the Notifications Center 'More' swipe action.")
swipeReadUnreadStack.label.text = viewModel.isRead
? CommonStrings.notificationsCenterMarkAsUnreadSwipe
: CommonStrings.notificationsCenterMarkAsReadSwipe
}
func updateProject(forViewModel viewModel: NotificationsCenterCellViewModel) {
// Show or hide project source label and image
if let projectText = viewModel.projectText {
projectSourceLabel.label.text = projectText
projectSourceLabel.isHidden = false
projectSourceImage.isHidden = true
} else if let projectIconName = viewModel.projectIconName {
projectSourceImage.image = UIImage(named: projectIconName)
projectSourceLabel.isHidden = true
projectSourceImage.isHidden = false
}
}
func updateMetaContent(forViewModel viewModel: NotificationsCenterCellViewModel) {
let footerText = viewModel.footerText ?? ""
metaLabel.text = footerText.isEmpty ? " " : viewModel.footerText
guard let footerIconType = viewModel.footerIconType else {
metaImageView.image = nil
return
}
let image: UIImage?
switch footerIconType {
case .custom(let iconName):
image = UIImage(named: iconName)
case .system(let iconName):
image = UIImage(systemName: iconName)
}
metaImageView.image = image
}
@objc func tappedMoreAction() {
delegate?.userDidTapMoreActionForCell(self)
}
@objc func tappedReadUnreadAction() {
delegate?.userDidTapMarkAsReadUnreadActionForCell(self)
UIAccessibility.post(notification: .screenChanged, argument: nil)
}
}
|
cdaebe3787f7c9d80c6d6cba67400269
| 42.612642 | 194 | 0.724293 | false | false | false | false |
blinksh/blink
|
refs/heads/raw
|
Blink/SmarterKeys/KBView.swift
|
gpl-3.0
|
1
|
////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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
// (at your option) any later version.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import UIKit
class KBView: UIView {
private var _leftSection: KBSection
private var _middleSection: KBSection
private var _rightSection: KBSection
private let _scrollView = UIScrollView()
private let _scrollViewLeftBorder = UIView()
private let _scrollViewRightBorder = UIView()
private let _indicatorLeft = UIView()
private let _indicatorRight = UIView()
private var _timer: Timer? = nil
private var _repeatingKeyView: KBKeyView? = nil
var repeatingSequence: String? = nil
var safeBarWidth: CGFloat = 0
var kbDevice: KBDevice = .detect() {
didSet {
if oldValue != kbDevice {
_updateSections()
}
}
}
var kbSizes: KBSizes = .portrait_iPhone_4
private var _onModifiersSet: Set<KBKeyView> = []
private var _untrackedModifiersSet: Set<KBKeyView> = []
weak var keyInput: SmarterTermInput? = nil
var lang: String = "" {
didSet {
if oldValue != lang && traitCollection.userInterfaceIdiom == .pad {
traits.hasSuggestions = ["zh-Hans", "zh-Hant", "ja-JP"].contains(lang)
_updateSections()
}
}
}
override var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: kbSizes.kb.height)
}
var traits: KBTraits = .initial {
didSet {
if traits != oldValue {
setNeedsLayout()
}
}
}
override init(frame: CGRect) {
let layout = kbDevice.layoutFor(lang: lang)
_leftSection = KBSection(keys:layout.left)
_middleSection = KBSection(keys:layout.middle)
_rightSection = KBSection(keys:layout.right)
super.init(frame: frame)
_scrollView.alwaysBounceVertical = false
_scrollView.alwaysBounceHorizontal = false
_scrollView.isDirectionalLockEnabled = true
_scrollView.showsHorizontalScrollIndicator = false
_scrollView.showsVerticalScrollIndicator = false
_scrollView.delaysContentTouches = false
_scrollView.contentInsetAdjustmentBehavior = .never
_scrollView.delegate = self
addSubview(_scrollView)
addSubview(_scrollViewLeftBorder)
addSubview(_scrollViewRightBorder)
if traitCollection.userInterfaceStyle == .light {
_scrollViewLeftBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.15)
_scrollViewRightBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.15)
} else {
_scrollViewLeftBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.45)
_scrollViewRightBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.45)
}
_indicatorLeft.backgroundColor = UIColor.blue.withAlphaComponent(0.45)
_indicatorRight.backgroundColor = UIColor.orange.withAlphaComponent(0.45)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func _updateSections() {
_leftSection.views.forEach { $0.removeFromSuperview() }
_middleSection.views.forEach { $0.removeFromSuperview() }
_rightSection.views.forEach { $0.removeFromSuperview() }
let layout = kbDevice.layoutFor(lang: lang)
_leftSection = KBSection(keys:layout.left)
_middleSection = KBSection(keys:layout.middle)
_rightSection = KBSection(keys:layout.right)
setNeedsLayout()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
traits.toggle(traitCollection.userInterfaceStyle == .light, on: .light, off: .dark)
if traitCollection.userInterfaceStyle == .light {
_scrollViewLeftBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.15)
_scrollViewRightBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.15)
} else {
_scrollViewLeftBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.45)
_scrollViewRightBorder.backgroundColor = UIColor.separator.withAlphaComponent(0.45)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let strictSpace = !traits.isHKBAttached && traits.hasSuggestions
self.kbSizes = kbDevice.sizesFor(portrait: traits.isPortrait)
let top: CGFloat = 0;
let height = kbSizes.kb.height
let iconWidth = kbSizes.key.widths.icon
let keyWidth = kbSizes.key.widths.key
let wideKeyWidth = kbSizes.key.widths.wide
let spacer = kbSizes.kb.spacer
let mainPadding = kbSizes.kb.padding
var middleLeft = mainPadding
var middleRight = frame.width - mainPadding
func viewWidth(_ shape: KBKeyShape) -> CGFloat {
switch shape {
case .icon: return iconWidth
case .wideKey: return wideKeyWidth
case .arrows: return wideKeyWidth
default: return keyWidth
}
}
let leftViews = _leftSection.apply(traits: traits, for: self, keyDelegate: self)
let middleViews = _middleSection.apply(traits: traits, for: _scrollView, keyDelegate: self)
let rightViews = _rightSection.apply(traits: traits, for: self, keyDelegate: self)
var x = middleLeft
for b in leftViews {
let width = viewWidth(b.key.shape)
b.frame = CGRect(x: x, y: top, width: width, height: height)
b.isHidden = strictSpace && b.frame.maxX - mainPadding >= safeBarWidth
x += width + spacer
middleLeft = x
}
x = middleRight
for b in rightViews.reversed() {
let width = viewWidth(b.key.shape)
x -= width
middleRight = x
b.frame = CGRect(x: x, y: top, width: width, height: height)
x -= spacer
}
middleRight -= spacer
x = 0
for b in middleViews {
let width = viewWidth(b.key.shape)
b.frame = CGRect(x: x, y: top, width: width, height: height)
b.isHidden = strictSpace && b.frame.minX + mainPadding <= bounds.width - safeBarWidth
x += width + spacer
}
_scrollView.frame = CGRect(x: middleLeft, y: top, width: middleRight - middleLeft, height: height)
let spaceLeft = _scrollView.frame.width - x
if spaceLeft > 0 {
// We can tune layout
let flexibleCount = middleViews.filter({ $0.key.isFlexible } ).count
if flexibleCount > 0 {
var flexibleWidth = CGFloat(flexibleCount) * keyWidth
flexibleWidth = (flexibleWidth + spaceLeft) / CGFloat(flexibleCount)
x = 0
for b in middleViews {
let width = b.key.isFlexible ? flexibleWidth : viewWidth(b.key.shape)
b.frame = CGRect(x: x, y: top, width: width, height: height)
x += width + spacer
}
}
}
_scrollView.contentSize = CGSize(width: x, height: height)
_scrollView.isHidden = strictSpace
var borderFrame = CGRect(x: middleLeft - 1, y: 9, width: 1, height: height - 19)
_scrollViewLeftBorder.frame = borderFrame
borderFrame.origin.x = middleRight - 1
_scrollViewRightBorder.frame = borderFrame
_updateScrollViewBorders()
}
func _updateScrollViewBorders() {
let size = _scrollView.contentSize
let width = _scrollView.frame.width
if size.width <= width {
_scrollViewLeftBorder.isHidden = true
_scrollViewRightBorder.isHidden = true
return
}
let offset = _scrollView.contentOffset
_scrollViewLeftBorder.isHidden = offset.x <= 0
_scrollViewRightBorder.isHidden = size.width - offset.x <= width
}
func turnOffUntracked() {
for keyView in _untrackedModifiersSet {
if !keyView.isTracking {
keyView.turnOff()
}
}
for keyView in _onModifiersSet {
if keyView.isTracking {
_untrackedModifiersSet.insert(keyView)
}
}
_untrackedModifiersSet = _onModifiersSet
}
func _startTimer(with view: KBKeyView) {
_repeatingKeyView = view
_timer?.invalidate()
keyViewTriggered(keyView: view, value: view.currentValue)
weak var weakSelf = self
_timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in
weakSelf?._continueTimer(interval: 0.1)
}
}
func _continueTimer(interval: TimeInterval) {
let repeatingKeyView = _repeatingKeyView
_timer?.invalidate()
_timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in
guard let view = repeatingKeyView
else {
return
}
view.key.sound.playIfPossible()
view.keyDelegate.keyViewTriggered(keyView: view, value: view.currentValue)
}
}
func stopRepeats() {
_timer?.invalidate()
_timer = nil
_repeatingKeyView = nil
}
}
extension KBView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
_updateScrollViewBorders()
}
}
extension KBView: KBKeyViewDelegate {
func keyViewAskedToCancelScroll(keyView: KBKeyView) {
_scrollView.panGestureRecognizer.dropTouches()
}
func keyViewOn(keyView: KBKeyView, value: KBKeyValue) {
stopRepeats()
_toggleModifier(kbKeyValue: value, value: true)
if value.isModifier {
_onModifiersSet.insert(keyView)
}
if (keyView.shouldAutoRepeat) {
_startTimer(with: keyView)
}
}
func keyViewOff(keyView: KBKeyView, value: KBKeyValue) {
_toggleModifier(kbKeyValue: value, value: false)
_onModifiersSet.remove(keyView)
stopRepeats()
}
func keyViewCanGoOff(keyView: KBKeyView, value: KBKeyValue) -> Bool {
if !value.isModifier {
return true
}
if _untrackedModifiersSet.contains(keyView) {
_untrackedModifiersSet.remove(keyView)
return true
}
_untrackedModifiersSet.insert(keyView)
return false
}
private func _toggleModifier(kbKeyValue: KBKeyValue, value: Bool) {
switch kbKeyValue {
case .cmd:
traits.toggle(value, on: .cmdOn , off: .cmdOff)
case .alt:
traits.toggle(value, on: .altOn , off: .altOff)
case .esc:
traits.toggle(value, on: .escOn , off: .escOff)
case .ctrl:
traits.toggle(value, on: .ctrlOn , off: .ctrlOff)
default: break
}
_reportModifiers()
}
func _reportModifiers() {
keyInput?.reportToolbarModifierFlags(traits.modifierFlags)
}
func reset() {
stopRepeats()
turnOffUntracked()
traits.toggle(false, on: .cmdOn , off: .cmdOff)
traits.toggle(false, on: .altOn , off: .altOff)
traits.toggle(false, on: .escOn , off: .escOff)
traits.toggle(false, on: .ctrlOn , off: .ctrlOff)
_reportModifiers()
}
func keyViewTriggered(keyView: KBKeyView, value: KBKeyValue) {
if value.isModifier {
return
}
if keyView !== _repeatingKeyView {
stopRepeats()
}
defer { turnOffUntracked() }
guard let keyInput = keyInput
else {
return
}
let keyCode = value.keyCode
var keyId = keyCode.id
keyId += ":\(value.text)"
var flags = traits.modifierFlags
if keyInput.trackingModifierFlags.contains(.shift) {
flags.insert(.shift)
}
if let input = value.input,
flags.rawValue > 0,
let (cmd, responder) = keyInput.matchCommand(input: input, flags: flags),
let action = cmd.action {
responder.perform(action, with: cmd)
return
}
if case .f = value {
flags.remove(.command)
}
keyInput.reportToolbarPress(flags, keyId: keyId)
}
func keyViewCancelled(keyView: KBKeyView) {
_untrackedModifiersSet.remove(keyView)
_onModifiersSet.remove(keyView)
if keyView === _repeatingKeyView {
stopRepeats()
}
}
func keyViewTouchesBegin(keyView: KBKeyView, touches: Set<UITouch>) {
guard
let touch = touches.first
else {
return
}
for recognizer in touch.gestureRecognizers ?? [] {
guard
recognizer !== _scrollView.panGestureRecognizer
else {
continue
}
recognizer.dropTouches()
}
}
}
|
4d4fbe8bb48e8fc6f0cee0da173d68ab
| 28.993166 | 102 | 0.65854 | false | false | false | false |
Diuit/DUMessagingUIKit-iOS
|
refs/heads/develop
|
DUMessagingUIKit/CustomViews.swift
|
mit
|
1
|
//
// CustomViews.swift
// DUMessagingUIKit
//
// Created by Pofat Diuit on 2016/6/3.
// Copyright © 2016年 duolC. All rights reserved.
//
import Foundation
import UIKit
/// This is a customized UILabel where their text alway align in top vertically
@IBDesignable open class TopAlignedLabel: UILabel {
override open func drawText(in rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
super.drawText(in: CGRect(x: 0, y: 0, width: self.frame.width, height: ceil(labelStringSize.height)))
} else {
super.drawText(in: rect)
}
}
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.black.cgColor
}
}
@IBDesignable open class DUAvatarImageView: UIImageView, CircleShapeView, DUImageResource {
// Automatically load the image right after its url is set
open var imagePath: String? = "" {
didSet {
if self.imagePath != "" {
self.loadImage() { [weak self] in
self?.image = self?.imageValue
}
}
}
}
}
open class RoundUIView: UIView, CircleShapeView { }
|
b99c310794fd2c5d04835c058d5acf33
| 37.478261 | 147 | 0.574576 | false | false | false | false |
MiezelKat/AWSense
|
refs/heads/master
|
AWSenseConnect/Shared/DataTransmissionMode.swift
|
mit
|
1
|
//
// DataTransmissionMode.swift
// AWSenseConnect
//
// Created by Katrin Haensel on 02/03/2017.
// Copyright © 2017 Katrin Haensel. All rights reserved.
//
import Foundation
//public enum DataTransmissionMode : String{
// case shortIntervall
// case longIntervall
//}
public struct DataTransmissionInterval{
public static let standard = DataTransmissionInterval(10)
private let lowerBound = 1.0
private let upperBound = 30.0
private var _intervallSeconds : Double = 10.0
/// The Interval in Seconds. Lower Bound 1, Upper bound 30
public var intervallSeconds : Double {
get{
return _intervallSeconds
}
set (val){
if(val > lowerBound && val < upperBound){
_intervallSeconds = val
}
}
}
public init(_ interv: Double){
intervallSeconds = interv
}
}
|
7445372608506a16b0735bcd31233284
| 21.071429 | 62 | 0.606257 | false | false | false | false |
amco/couchbase-lite-ios
|
refs/heads/master
|
Swift/Parameters.swift
|
apache-2.0
|
1
|
//
// Parameters.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// A Parameters object used for setting values to the query parameters defined in the query.
public class Parameters {
/// Initializes the Parameters's builder.
public convenience init() {
self.init(parameters: nil, readonly: false)
}
/// Initializes the Parameters's builder with the given parameters.
///
/// - Parameter parameters: The parameters.
public convenience init(parameters: Parameters?) {
self.init(parameters: parameters, readonly: false)
}
/// Gets a parameter's value.
///
/// - Parameter name: The parameter name.
/// - Returns: The parameter value.
public func value(forName name: String) -> Any? {
return self.params[name];
}
/// Set a boolean value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The boolean value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setBoolean(_ value: Bool, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set a date value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The date value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setDate(_ value: Date?, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set a double value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The double value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setDouble(_ value: Double, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set a float value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The float value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setFloat(_ value: Float, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set an int value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The int value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setInt(_ value: Int, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set an int64 value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The int64 value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setInt64(_ value: Int64, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set a String value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The String value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setString(_ value: String?, forName name: String) -> Parameters {
return setValue(value, forName: name)
}
/// Set a value to the query parameter referenced by the given name. A query parameter
/// is defined by using the Expression's parameter(_ name: String) function.
///
/// - Parameters:
/// - value: The value.
/// - name: The parameter name.
/// - Returns: The self object.
@discardableResult public func setValue(_ value: Any?, forName name: String) -> Parameters {
checkReadOnly()
params[name] = value
return self
}
// MARK: Internal
private let readonly: Bool
var params: Dictionary<String, Any>
init(parameters: Parameters?, readonly: Bool) {
self.params = parameters != nil ? parameters!.params : [:]
self.readonly = readonly
}
func checkReadOnly() {
if self.readonly {
fatalError("This parameters object is readonly.")
}
}
func toImpl() -> CBLQueryParameters {
let params = CBLQueryParameters()
for (name, value) in self.params {
params.setValue(value, forName: name)
}
return params
}
}
|
fbcc3cd0f12515d6bfadb9c30af18651
| 35.459627 | 100 | 0.633901 | false | false | false | false |
noppoMan/SwiftKnex
|
refs/heads/master
|
Sources/Mysql/Protocol/Packet/PrepareResultPacket.swift
|
mit
|
1
|
//
// PrepareResultPacket.swift
// SwiftKnex
//
// Created by Yuki Takei on 2017/01/12.
//
//
enum PrepareResultPacketError: Error {
case failedToParsePrepareResultPacket
}
public struct PrepareResultPacket {
let id: UInt32
let columnCount: UInt16
let paramCount: UInt16
init?(bytes: [UInt8]) throws {
guard let byte = bytes.first else {
return nil
}
switch byte {
case 0x00:
// statement id [4 bytes]
let id = bytes[1..<5].uInt32()
// Column count [16 bit uint]
let columnCount = bytes[5..<7].uInt16()
// Param count [16 bit uint]
let paramCount = bytes[7..<9].uInt16()
self.id = id
self.columnCount = columnCount
self.paramCount = paramCount
default:
throw createErrorFrom(errorPacket: bytes)
}
}
}
|
da6cec8bcab6c9e43190c03f98a25445
| 21.906977 | 53 | 0.519797 | false | false | false | false |
cfilipov/MuscleBook
|
refs/heads/master
|
MuscleBook/ExerciseStatisticsViewController.swift
|
gpl-3.0
|
1
|
/*
Muscle Book
Copyright (C) 2016 Cristian Filipov
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
(at your option) 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 UIKit
import Eureka
class ExerciseStatisticsViewController : FormViewController {
private let db = DB.sharedInstance
private let exerciseRef: ExerciseReference
let numberFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = 0
return formatter
}()
private var exerciseID: Int64 {
return exerciseRef.exerciseID!
}
init(exercise: ExerciseReference) {
self.exerciseRef = exercise
super.init(style: .Grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView?.contentInset = UIEdgeInsetsMake(-36, 0, 0, 0)
title = exerciseRef.name
form
+++ Section()
<<< LabelRow() {
$0.title = "Name"
$0.value = exerciseRef.name
}
<<< PunchcardRow() {
$0.tag = "punchcard"
$0.value = ExercisePunchcardDelegate(exerciseID: self.exerciseID)
}
<<< IntRow() {
$0.title = "Workouts"
$0.tag = "workouts"
$0.hidden = "$workouts == nil"
$0.disabled = true
}
<<< IntRow() {
$0.title = "Sets"
$0.tag = "sets"
$0.hidden = "$sets == nil"
$0.disabled = true
}
+++ Section("Records") {
$0.tag = "records"
$0.hidden = Condition.Function([]) { form -> Bool in
return (form.sectionByTag("records")?.count ?? 0) > 0 ? false : true
}
}
<<< DecimalRow() {
$0.title = "RM"
$0.tag = "rm"
$0.hidden = "$rm == nil"
$0.disabled = true
$0.formatter = self.numberFormatter
$0.cellUpdate { cell, row in
cell.accessoryType = row.value == nil ? .None : .DisclosureIndicator
}
}
<<< DecimalRow() {
$0.title = "1RM"
$0.tag = "rm1"
$0.hidden = "$rm1 == nil"
$0.disabled = true
$0.formatter = self.numberFormatter
$0.cellUpdate { cell, row in
cell.accessoryType = row.value == nil ? .None : .DisclosureIndicator
}
}
<<< DecimalRow() {
$0.title = "e1RM"
$0.tag = "e1rm"
$0.hidden = "$e1rm == nil"
$0.disabled = true
$0.formatter = self.numberFormatter
$0.cellUpdate { cell, row in
cell.accessoryType = row.value == nil ? .None : .DisclosureIndicator
}
}
<<< DecimalRow() {
$0.title = "Volume"
$0.tag = "past_volume"
$0.hidden = "$past_volume == nil"
$0.disabled = true
$0.formatter = self.numberFormatter
$0.cellUpdate { cell, row in
cell.accessoryType = row.value == nil ? .None : .DisclosureIndicator
}
}
updateRows()
}
private func updateRows() {
form.rowByTag("workouts")?.value = db.count(Workout.self, exerciseID: exerciseID)
form.rowByTag("sets")?.value = db.count(Exercise.self, exerciseID: exerciseID)
if let row = form.rowByTag("rm") as? DecimalRow {
let maxWeight = db.maxRM(exerciseID: exerciseID)
row.value = maxWeight?.input.weight
row.onCellSelection { _, _ in self.showWorkset(maxWeight) }
}
if let row = form.rowByTag("rm1") as? DecimalRow {
let max1rm = db.max1RM(exerciseID: exerciseID)
row.value = max1rm?.input.weight
row.onCellSelection { _, _ in self.showWorkset(max1rm) }
}
if let row = form.rowByTag("e1rm") as? DecimalRow {
let maxe1rm = db.maxE1RM(exerciseID: exerciseID)
row.value = maxe1rm?.calculations.e1RM
row.onCellSelection { _, _ in self.showWorkset(maxe1rm) }
}
if let row = form.rowByTag("past_volume") as? DecimalRow {
let maxvol = db.maxVolume(exerciseID: exerciseID)
row.value = maxvol?.calculations.volume
row.onCellSelection { _, _ in self.showWorkset(maxvol) }
}
form.sectionByTag("records")?.evaluateHidden()
}
private func showWorkset(workset: Workset?) {
let vc = WorksetViewController(workset: workset)
self.showViewController(vc, sender: nil)
}
}
private class ExercisePunchcardDelegate: PunchcardDelegate {
private let db = DB.sharedInstance
private let cal = NSCalendar.currentCalendar()
private let activations: [NSDate: ActivationLevel]
private let exerciseID: Int64
init(exerciseID: Int64) {
self.exerciseID = exerciseID
activations = try! db.activationByDay(exerciseID: exerciseID)
}
override func calendarGraph(calendarGraph: EFCalendarGraph!, valueForDate date: NSDate!, daysAfterStartDate: UInt, daysBeforeEndDate: UInt) -> AnyObject! {
guard let activation = activations[cal.startOfDayForDate(date)] else { return 0 }
switch activation {
case .None: return 0
case .Light: return 1
case .Medium: return 1
case .High: return 1
case .Max: return 5
}
}
}
|
687366e4ed1ca02d518043a93cad60e2
| 31.52381 | 159 | 0.574752 | false | false | false | false |
anicolaspp/rate-my-meetings-ios
|
refs/heads/master
|
RateMyMeetings/EventManager.swift
|
mit
|
1
|
//
// EventManager.swift
// RateMyMeetings
//
// Created by Nicolas Perez on 11/24/15.
// Copyright © 2015 Nicolas Perez. All rights reserved.
//
import Foundation
import EventKit
import Parse
class EventManager {
let eventStore: EKEventStore
var eventsAccessGranted: Bool
var calendar: EKCalendar?
let user: User?
let calendarRepository: CalendarRepository?
init(user: User, withCalendarRepository: CalendarRepository) {
self.eventStore = EKEventStore()
self.user = user
self.calendarRepository = withCalendarRepository
let userDeaults = NSUserDefaults()
if let key = userDeaults.valueForKey("eventkit_events_access_granted") {
self.eventsAccessGranted = key as! Bool
}
else {
self.eventsAccessGranted = false
}
self.setStoredCalendar()
}
private func setStoredCalendar() {
if let inUseCalendar = self.calendarRepository?.getInUseCalendarFor(self.user!) {
self.calendar = self.eventStore.calendarWithIdentifier(inUseCalendar.localEntity)
}
}
func setEventsAccessGranted(accessGranted: Bool) {
let userDeaults = NSUserDefaults()
userDeaults.setValue(accessGranted, forKey: "eventkit_events_access_granted")
}
func getLocalEventCalendars() -> [EKCalendar] {
let calendars = eventStore.calendarsForEntityType(.Event)
return calendars
}
func getEventsWithInitialMonth(monthsAgo: Int, monthsInTheFuture: Int) -> [EKEvent] {
let calendar = NSCalendar.currentCalendar()
let oneMonthAgoComponnents = NSDateComponents()
let oneMonthAgo = calendar.dateByAddingComponents(oneMonthAgoComponnents, toDate: NSDate(), options: NSCalendarOptions.MatchNextTime)
let oneMonthFromNowComponnent = NSDateComponents()
oneMonthFromNowComponnent.day = monthsInTheFuture
let oneMonthFromNow = calendar.dateByAddingComponents(oneMonthFromNowComponnent, toDate: NSDate(), options: NSCalendarOptions.MatchNextTime)
let predicate = eventStore.predicateForEventsWithStartDate(oneMonthAgo!, endDate: oneMonthFromNow!, calendars: [self.calendar!])
let events = eventStore.eventsMatchingPredicate(predicate)
return events
}
func getEventForDay(day: NSDate) -> [EKEvent] {
let todayComponnents = day.atMidnight()
let tomorrowComponnent = NSDate(timeInterval: NSTimeInterval.init(86400), sinceDate: day)
let predicate = eventStore.predicateForEventsWithStartDate(todayComponnents, endDate: tomorrowComponnent, calendars: [self.calendar!])
let events = eventStore.eventsMatchingPredicate(predicate)
return events
}
}
|
1e7375920b6a93ea97367f1538520d88
| 31.465909 | 148 | 0.681834 | false | false | false | false |
nkirby/Humber
|
refs/heads/master
|
_lib/HMGithub/_src/Realm/GithubAccount.swift
|
mit
|
1
|
// =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import RealmSwift
// =======================================================
public class GithubAccount: Object {
public dynamic var avatarURL = ""
public dynamic var bio = ""
public dynamic var blog = ""
public dynamic var collaborators = 0
public dynamic var company = ""
// public dynamic var createdAt = 0
public dynamic var email = ""
public dynamic var followers = 0
public dynamic var following = 0
public dynamic var hireable = false
public dynamic var htmlURL = ""
public dynamic var userID = ""
public dynamic var location = ""
public dynamic var login = ""
public dynamic var name = ""
public dynamic var ownedPrivateRepos = 0
public dynamic var privateGists = 0
public dynamic var publicGists = 0
public dynamic var publicRepos = 0
public dynamic var siteAdmin = 0
public dynamic var totalPrivateRepos = 0
public dynamic var type = ""
// public dynamic var updatedAt = 0
public dynamic var url = ""
public var followingUsers = List<GithubUser>()
public var followerUsers = List<GithubUser>()
public var gists = List<GithubGist>()
public override class func primaryKey() -> String {
return "userID"
}
}
|
aabfde186ce74bc0624d67a2e62fd339
| 31.181818 | 58 | 0.589689 | false | false | false | false |
ormaa/Bluetooth-LE-IOS-Swift
|
refs/heads/master
|
Peripheral Manager/Shared/BLE_PeripheralManager.swift
|
mit
|
1
|
//
// BLECentralManager.swift
// BlueToothCentral
//
// Created by Olivier Robin on 30/10/2016.
// Copyright © 2016 fr.ormaa. All rights reserved.
//
import Foundation
import CoreBluetooth
#if os(iOS) || os(watchOS) || os(tvOS)
import UserNotifications
#elseif os(OSX)
import Cocoa
#else
// something else :o)
#endif
// Apple documentation :
// https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html
// UUID of peripheral service, and characteristics
// can be generated using "uuidgen" under osx console
let peripheralName = "ORMAA_1.0"
// Service
let BLEService = "00001901-0000-1000-8000-00805f9b34fb" // generic service
// Characteristics
let CH_READ = "2AC6A7BF-2C60-42D0-8013-AECEF2A124C0"
let CH_WRITE = "9B89E762-226A-4BBB-A381-A4B8CC6E1105"
let TextToAdvertise = "hey hey dude. what's up?" // < 28 bytes needed.
var TextToNotify = "Notification: " // < 28 bytes needed ???
// BlueTooth do not work if it not instanciated, called, managed, from a uiview controller, linked to a .xib, or storyboard
//
class BLEPeripheralManager : NSObject, CBPeripheralManagerDelegate {
// use class variable, instead of variable in function :
// allow to be retained in memory. if not, Swift can get ridd of them when it want.
var localPeripheralManager: CBPeripheralManager! = nil
var localPeripheral:CBPeripheral? = nil
var createdService = [CBService]()
var notifyCharac: CBMutableCharacteristic? = nil
var notifyCentral: CBCentral? = nil
// timer used to retry to scan for peripheral, when we don't find it
var notifyValueTimer: Timer?
// Delegate to a parent.will allow to display thing, or send value
var delegate: BLEPeripheralProtocol?
var cpt = 0
// start the PeripheralManager
//
func startBLEPeripheral() {
delegate?.logToScreen( "startBLEPeripheral")
delegate?.logToScreen( "Discoverable name : " + peripheralName)
delegate?.logToScreen( "Discoverable service :\n" + BLEService)
// start the Bluetooth periphal manager
localPeripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
// Stop advertising.
//
func stopBLEPeripheral() {
delegate?.logToScreen( "stopBLEPeripheral")
self.localPeripheralManager.removeAllServices()
self.localPeripheralManager.stopAdvertising()
}
// delegate
//
// Receive bluetooth state
//
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager)
{
// get a human readable value :o)
let state = getState(peripheral: peripheral)
delegate!.logToScreen( "peripheralManagerDidUpdateState is : \(state)")
if peripheral.state == .poweredOn {
self.createServices()
}
else {
delegate?.logToScreen( "cannot create services. state is : " + getState(peripheral: peripheral))
}
}
// Create 1 service
// 2 Characteristics : 1 for read, 1 for write.
//
func createServices() {
delegate?.logToScreen( "create Services")
// service
let serviceUUID = CBUUID(string: BLEService)
let service = CBMutableService(type: serviceUUID, primary: true)
// characteristic
var chs = [CBMutableCharacteristic]()
// Read characteristic
delegate?.logToScreen( "Charac. read : \n" + CH_READ)
let characteristic1UUID = CBUUID(string: CH_READ)
let properties: CBCharacteristicProperties = [.read, .notify ]
let permissions: CBAttributePermissions = [.readable]
let ch = CBMutableCharacteristic(type: characteristic1UUID, properties: properties, value: nil, permissions: permissions)
chs.append(ch)
// Write characteristic
delegate?.logToScreen( "Charac. write : \n" + CH_WRITE)
let characteristic2UUID = CBUUID(string: CH_WRITE)
let properties2: CBCharacteristicProperties = [.write, .notify ]
let permissions2: CBAttributePermissions = [.writeable]
let ch2 = CBMutableCharacteristic(type: characteristic2UUID, properties: properties2, value: nil, permissions: permissions2)
chs.append(ch2)
// Create the service, add the characteristic to it
service.characteristics = chs
createdService.append(service)
localPeripheralManager.add(service)
}
// delegate
// service + Charactersitic added to peripheral
//
func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?){
if error != nil {
delegate?.logToScreen( ("Error adding services: \(error!.localizedDescription)"))
}
else {
delegate?.logToScreen( "peripheralManager didAdd service : \(service.uuid.uuidString)")
// Create an advertisement, using the service UUID
let advertisement: [String : Any] = [CBAdvertisementDataServiceUUIDsKey : [service.uuid]] //CBAdvertisementDataLocalNameKey: peripheralName]
//28 bytes maxu !!!
// only 10 bytes for the name
// https://developer.apple.com/reference/corebluetooth/cbperipheralmanager/1393252-startadvertising
// start the advertisement
delegate?.logToScreen( "Advertisement datas: ")
delegate?.logToScreen( String(describing: advertisement))
self.localPeripheralManager.startAdvertising(advertisement)
delegate?.logToScreen( "Service added to peripheral.")
}
}
// Advertising done
//
func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?){
if error != nil {
delegate?.logToScreen( ("peripheralManagerDidStartAdvertising Error :\n \(error!.localizedDescription)"))
}
else {
delegate?.logToScreen( "peripheralManagerDidStartAdvertising - started.\n")
}
}
// Central request to be notified to a charac.
//
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
delegate?.logToScreen( "peripheralManager didSubscribeTo characteristic " +
characteristic.uuid.uuidString.prefix(6))
if characteristic.uuid.uuidString == CH_READ {
delegate?.logToScreen( "Central manager requested to read values by BLE notification")
self.notifyCharac = characteristic as? CBMutableCharacteristic
self.notifyCentral = central
// start a timer, which will update the value, every xyz seconds.
self.notifyValueTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.notifyValue), userInfo: nil, repeats: true)
}
}
// called when Central manager send read request
//
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
delegate?.logToScreen( "\nperipheralManager didReceiveRead request")
delegate?.logToScreen( "request uuid: " + request.characteristic.uuid.uuidString)
// prepare advertisement data
let data: Data = TextToAdvertise.data(using: String.Encoding.utf16)!
request.value = data //characteristic.value
delegate?.logToScreen( "send : \(TextToAdvertise)" )
// Respond to the request
localPeripheralManager.respond( to: request, withResult: .success)
// acknowledge : ok
peripheral.respond(to: request, withResult: CBATTError.success)
}
// called when central manager send write request
//
public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
delegate?.logToScreen( "\nperipheralManager didReceiveWrite request")
for r in requests {
delegate?.logToScreen( "request uuid: " + r.characteristic.uuid.uuidString)
}
if requests.count > 0 {
let str = NSString(data: requests[0].value!, encoding:String.Encoding.utf16.rawValue)!
print("value sent by central Manager :\n" + String(describing: str))
delegate?.logToScreen( "string received \(str) ")
} else {
print("nothing sent by centralManager")
delegate?.logToScreen( "NO string received")
}
peripheral.respond(to: requests[0], withResult: CBATTError.success)
}
func respond(to request: CBATTRequest, withResult result: CBATTError.Code) {
delegate?.logToScreen( "response requested")
}
func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
delegate?.logToScreen( "peripheral name changed")
}
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
delegate?.logToScreen( "peripheral service modified")
}
func peripheral(_ peripheral: CBPeripheral, willRestoreState: [String : Any]) {
delegate?.logToScreen("Will restore peripheral to central connection")
}
}
|
ba961de1a5efaf9201e3120fea4da04d
| 33.589091 | 210 | 0.658221 | false | false | false | false |
txaidw/TWControls
|
refs/heads/master
|
TWSpriteKitUtils Demo/SwitchesDemoScene.swift
|
mit
|
1
|
//
// ButtonsDemoScene.swift
// TWSpriteKitUtils
//
// Created by Txai Wieser on 9/17/15.
// Copyright © 2015 Txai Wieser. All rights reserved.
//
import SpriteKit
import TWSpriteKitUtils
class SwitchesDemoScene: SKScene {
override func didMove(to view: SKView) {
/* Setup your scene here */
TWControl.defaultTouchDownSoundFileName = "touchDownDefault.wav"
TWControl.defaultTouchUpSoundFileName = "touchUpDefault.wav"
TWControl.defaultDisabledTouchDownFileName = "touchDown_disabled.wav"
textureButton.touchDownSoundFileName = "touchDown.wav"
textureButton.touchUpSoundFileName = "touchUp.wav"
textureSwitch.touchDownSoundFileName = "touchDown.wav"
textureSwitch.touchUpSoundFileName = "touchUp.wav"
backgroundColor = SKColor(red: 80/255, green: 227/255, blue: 194/255, alpha: 1)
addChild(switchesContainer)
switchesContainer.addChild(colorSwitch)
switchesContainer.addChild(textureSwitch)
switchesContainer.addChild(textSwitch)
addChild(buttonsContainer)
buttonsContainer.addChild(colorButton)
buttonsContainer.addChild(textureButton)
buttonsContainer.addChild(textButton)
addChild(SKSpriteNode(color: UIColor.red, size: CGSize(width: 200, height: 200)))
colorSwitch.addClosure(.touchUpInside, target: self) { (scene, control) -> () in
scene.textureSwitch.enabled = control.selected
scene.textSwitch.enabled = control.selected
}
textureSwitch.addClosure(.touchUpInside, target: self) { (scene, control) -> () in
scene.colorSwitch.enabled = control.selected
scene.textSwitch.enabled = control.selected
}
textSwitch.addClosure(.touchUpInside, target: self) { (scene, control) -> () in
scene.colorSwitch.enabled = control.selected
scene.textureSwitch.enabled = control.selected
print(control.selected)
}
colorButton.addClosure(.touchUpInside, target: self) { (scene, control) -> () in
scene.textureButton.enabled = !scene.textureButton.enabled
scene.textButton.enabled = !scene.textButton.enabled
}
textureButton.addClosure(.touchUpInside, target: self) { (scene, control) -> () in
scene.colorButton.enabled = !scene.colorButton.enabled
scene.textButton.enabled = !scene.textButton.enabled
}
textButton.addClosure(.touchUpInside, target: self) { (scene, control) -> () in
scene.colorButton.enabled = !scene.colorButton.enabled
scene.textureButton.enabled = !scene.textureButton.enabled
}
}
// SWITCHES
lazy var switchesContainer:SKSpriteNode = {
let n = SKSpriteNode(color: SKColor.white, size: CGSize(width: 220, height: 320))
n.position = CGPoint(x: self.frame.midX, y: self.frame.height - n.size.height/2 - 30)
let l = SKLabelNode(text: "Switches")
l.fontName = "Helvetica"
l.fontColor = SKColor.black
l.position = CGPoint(x: 0, y: n.size.height/2-l.frame.height - 10)
n.addChild(l)
return n
}()
lazy var colorSwitch:TWSwitch = {
let s = TWSwitch(size: CGSize(width: 102, height: 40), normalColor: SKColor.blue, selectedColor: SKColor.orange)
s.disabledStateColor = SKColor.gray
s.setDisabledStateLabelText("DISABLED")
s.setNormalStateLabelText("ON")
s.setSelectedStateLabelText("OFF")
s.setAllStatesLabelFontSize(20)
s.setAllStatesLabelFontName("Helvetica")
s.position = CGPoint(x: 0, y: 40)
return s
}()
lazy var textureSwitch:TWSwitch = {
let s = TWSwitch(normalTexture: SKTexture(imageNamed: "switch_off"), selectedTexture: SKTexture(imageNamed: "switch_on"))
s.disabledStateTexture = SKTexture(imageNamed: "switch_d")
s.highlightedStateSingleTexture = SKTexture(imageNamed: "button_n")
s.position = CGPoint(x: 0, y: -40)
return s
}()
lazy var textSwitch:TWSwitch = {
let s = TWSwitch(normalText: "ON", selectedText: "OFF")
s.setDisabledStateLabelText("DISABLED")
s.setHighlightedStateSingleLabelText("HIGH")
s.setAllStatesLabelFontColor(SKColor.black)
s.position = CGPoint(x: 0, y: -120)
return s
}()
// BUTTONS
lazy var buttonsContainer:SKSpriteNode = {
let n = SKSpriteNode(color: SKColor.white, size: CGSize(width: 220, height: 320))
n.position = CGPoint(x: self.frame.midX, y: n.size.height/2 + 30)
let l = SKLabelNode(text: "Buttons")
l.fontName = "Helvetica"
l.fontColor = SKColor.black
l.position = CGPoint(x: 0, y: n.size.height/2-l.frame.height - 10)
n.addChild(l)
return n
}()
lazy var colorButton:TWButton = {
let b = TWButton(size: CGSize(width: 102, height: 40), normalColor: SKColor.purple, highlightedColor: nil)
b.disabledStateColor = SKColor.gray
b.setDisabledStateLabelText("DISABLED")
b.setNormalStateLabelText("PLAY")
b.setHighlightedStateSingleLabelText("PRESSED")
b.setAllStatesLabelFontSize(20)
b.setAllStatesLabelFontName("Helvetica")
b.position = CGPoint(x: 0, y: 40)
return b
}()
lazy var textureButton:TWButton = {
let b = TWButton(normalTexture: SKTexture(imageNamed: "button_n"), highlightedTexture: SKTexture(imageNamed: "button_h"))
b.disabledStateTexture = SKTexture(imageNamed: "button_d")
b.position = CGPoint(x: 0, y: -40)
return b
}()
lazy var textButton:TWButton = {
let b = TWButton(normalText: "PLAY", highlightedText: "PRESSED")
b.setDisabledStateLabelText("DISABLED")
b.setAllStatesLabelFontColor(SKColor.black)
b.position = CGPoint(x: 0, y: -120)
return b
}()
}
|
974d29a3fa4a4708c9bc7760b4eae390
| 38.423077 | 129 | 0.63187 | false | false | false | false |
Shivol/Swift-CS333
|
refs/heads/master
|
playgrounds/uiKit/UIKitCatalog.playground/Pages/UIToolbar.xcplaygroundpage/Contents.swift
|
mit
|
2
|
import UIKit
import PlaygroundSupport
class Controller {
let label: UILabel!
let imageView: UIImageView!
@objc func systemButtonTouched(sender: UIBarButtonItem) {
imageView.image = nil
// There is no convenient way to distinguish between system buttons
label.text = "System button"
}
@objc func imageButtonTouched(sender: UIBarButtonItem) {
if let fullColorImage = sender.image?.withRenderingMode(.alwaysOriginal) {
imageView.image = fullColorImage
label.text = ""
}
}
@objc func fakeButtonTouched(sender: UIButton) {
imageView.image = nil
label.text = sender.titleLabel?.text
}
init(with label: UILabel){
self.label = label
self.imageView = UIImageView(frame: label.bounds)
self.label.addSubview(imageView)
imageView.contentMode = .center
}
}
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 250, height: 250))
containerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
let displayLabel = UILabel(frame: CGRect(x: 0, y: 200, width: 250, height: 50))
displayLabel.textAlignment = .center
containerView.addSubview(displayLabel)
let controller = Controller(with: displayLabel)
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
toolbar.items = [
UIBarButtonItem(barButtonSystemItem: .trash, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .bookmarks, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .camera, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .organize, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .action, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .compose, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .reply, target: controller, action: #selector(Controller.systemButtonTouched(sender:))),
UIBarButtonItem(barButtonSystemItem: .search, target: controller, action: #selector(Controller.systemButtonTouched(sender:)))
]
containerView.addSubview(toolbar)
let custombar = UIToolbar(frame: CGRect(x: 0, y: 50, width: 250, height: 30))
custombar.tintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
custombar.setBackgroundImage(#imageLiteral(resourceName: "gradient.png"), forToolbarPosition: .any, barMetrics: .default)
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let titles = ["Add", "Me", "To", "The", "Bar" ]
custombar.items = []
custombar.items?.append(space)
for title in titles {
// UIBarButtonItem(title: title, style: UIBarButtonItemStyle.done, target: controller, action: #selector(Controller.buttonTouched(sender:)))
// Default button has weird alignment issues!
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 30))
button.setTitle(title, for: .normal)
button.addTarget(controller, action: #selector(Controller.fakeButtonTouched(sender:)), for: .touchUpInside)
let barItem = UIBarButtonItem(customView: button)
custombar.items?.append(barItem)
custombar.items?.append(space)
}
containerView.addSubview(custombar)
let imageBar = UIToolbar(frame: CGRect(x: 0, y: 100, width: 250, height: 45))
imageBar.clipsToBounds = true
imageBar.barTintColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
imageBar.tintColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
imageBar.items = [
UIBarButtonItem(image: "🚶".image, style: .plain, target: controller, action: #selector(Controller.imageButtonTouched(sender:))),
space,
UIBarButtonItem(image: "🚲".image, style: .plain, target: controller, action: #selector(Controller.imageButtonTouched(sender:))),
space,
UIBarButtonItem(image: "🚘".image, style: .plain, target: controller, action: #selector(Controller.imageButtonTouched(sender:))),
space,
UIBarButtonItem(image: "🚂".image, style: .plain, target: controller, action: #selector(Controller.imageButtonTouched(sender:))),
space,
UIBarButtonItem(image: "✈️".image, style: .plain, target: controller, action: #selector(Controller.imageButtonTouched(sender:)))
]
containerView.addSubview(imageBar)
PlaygroundPage.current.liveView = containerView
|
dab0da695cc7e00967a6aa1e6811844e
| 45.60396 | 144 | 0.728702 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift
|
refs/heads/master
|
Solutions/Solutions/Easy/Easy_067_Add_Binary.swift
|
mit
|
3
|
/*
https://leetcode.com/problems/add-binary/
#67 Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Inspired by @makuiyu at https://leetcode.com/discuss/25593/short-code-by-c
*/
import Foundation
private extension String {
subscript (index: Int) -> Character {
return self[self.startIndex.advancedBy(index)]
}
}
struct Easy_067_Add_Binary {
static func addBinary(a a: String, b: String) -> String {
var s = ""
var c: Int = 0
var i = a.characters.count - 1
var j = b.characters.count - 1
let characterDict: [Character: Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
]
let intDict: [Int: String] = [
0: "0",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
]
while i >= 0 || j >= 0 || c == 1 {
c += i >= 0 ? characterDict[a[i--]]! : 0
c += j >= 0 ? characterDict[b[j--]]! : 0
s = intDict[c%2]! + s
c /= 2
}
return s
}
}
|
f58c2340de28ae8aefc70a707edee699
| 20.296875 | 74 | 0.406755 | false | false | false | false |
pawanpoudel/SwiftNews
|
refs/heads/master
|
SwiftNews/ExternalDependencies/Database/ArticleCoreDataManager.swift
|
mit
|
1
|
import CoreData
class ArticleCoreDataManager : ArticleRepository {
// MARK: - Initializing a data manager
private let coreDataStack: CoreDataStack
init(coreDataStack: CoreDataStack) {
self.coreDataStack = coreDataStack
}
// MARK: - Saving an article
func saveArticle(article: Article) {
createManagedArticleFromArticle(article)
coreDataStack.saveMainQueueContext()
}
private func createManagedArticleFromArticle(article: Article) -> ManagedArticle {
let managedArticle = NSEntityDescription.insertNewObjectForEntityForName("ManagedArticle",
inManagedObjectContext: coreDataStack.mainQueueContext!) as! ManagedArticle
if let uniqueId = article.uniqueId {
managedArticle.uniqueId = uniqueId
}
if let title = article.title {
managedArticle.title = title
}
if let summary = article.summary {
managedArticle.summary = summary
}
if let sourceUrl = article.sourceUrl {
managedArticle.sourceUrl = sourceUrl
}
if let publisher = article.publisher {
managedArticle.publisher = publisher
}
if let imageUrl = article.imageUrl {
managedArticle.imageUrl = imageUrl
}
if let publishedDate = article.publishedDate {
managedArticle.publishedDate = publishedDate
}
return managedArticle
}
// MARK: - Verifying existence of an article
func doesArticleExist(article: Article) -> Bool {
let managedArticle = fetchManagedArticleWithUniqueId(article.uniqueId!)
return managedArticle != nil ? true : false
}
// MARK: - Retrieving articles
func articleWithUniqueId(uniqueId: String) -> Article? {
if let managedArticle = fetchManagedArticleWithUniqueId(uniqueId) {
return createArticleFromManagedArticle(managedArticle)
}
return nil
}
func createArticleFromManagedArticle(managedArticle: ManagedArticle) -> Article {
let article = Article()
article.uniqueId = managedArticle.uniqueId;
article.title = managedArticle.title;
article.summary = managedArticle.summary;
article.sourceUrl = managedArticle.sourceUrl;
article.imageUrl = managedArticle.imageUrl;
article.publisher = managedArticle.publisher;
article.publishedDate = managedArticle.publishedDate;
return article;
}
private func fetchManagedArticleWithUniqueId(uniqueId: String) -> ManagedArticle? {
let fetchRequest = NSFetchRequest(entityName: "ManagedArticle")
fetchRequest.predicate = NSPredicate(format: "uniqueId like \(uniqueId)")
var error: NSError?
if let articles = coreDataStack.mainQueueContext?.executeFetchRequest(fetchRequest, error: &error)
where count(articles) > 0
{
return articles.first as? ManagedArticle
}
println("Error occurred while retrieving an article with unique ID: \(error?.localizedDescription)")
return nil
}
}
|
4508094826edcc1a722aa0e1f889a4bc
| 32.060606 | 108 | 0.640086 | false | false | false | false |
mojidabckuu/content
|
refs/heads/master
|
Content/Classes/Content+AnyContent.swift
|
mit
|
1
|
//
// Content+AnyContent.swift
// Alamofire
//
// Created by Vlad Gorbenko on 10/12/2017.
//
import Foundation
extension Content: AnyContent {
public func insert(_ newElement: Any, at index: Int, animated: Bool) {
guard let realElement = newElement as? Model else { return }
self.insert(realElement, at: index, animated: animated)
}
public func insert(contentsOf models: [Any], at index: Int, animated: Bool) {
guard let realElements = models as? [Model] else { return }
self.insert(contentsOf: realElements, at: index, animated: animated)
}
public func delete(_ element: Any) {
guard let realElement = element as? Model else { return }
self.delete(items: [realElement])
}
public func delete(contentsOf models: Any) {
guard let realElements = models as? [Model] else { return }
self.delete(items: realElements)
}
public func move(_ element: Any, to destination: Int) {
guard let realElement = element as? Model else { return }
guard let index = self.index(of: realElement) else { return }
self.move(from: index, to: destination)
}
//MARK: -
public func reload() {
self.delegate?.reload()
}
public func reload(_ element: Any, animated: Bool) {
guard let realElement = element as? Model else { return }
self.reload(realElement, animated: true)
}
public func reload(contentsOf models: [Any], animated: Bool) {
guard let realElements = models as? [Model] else { return }
self.reload(models, animated: true)
}
//MARK: -
public func update(_ block: () -> (), completion: (() -> ())?) {
self.delegate?.update(block, completion: completion)
}
public func update(_ block: () -> ()) {
self.delegate?.update(block, completion: nil)
}
//MARK: - Navigation
public func scrollToBegining() {
self.delegate?.scrollToTop()
}
public func scrollToEnd() {
self.delegate?.scrollToBottom()
}
public func scrollTo(_ element: Any) {
guard let realElement = element as? Model else { return }
self.delegate?.scroll(to: realElement, at: .none, animated: true)
}
public func scrollTo(_ model: Model) {
self.delegate?.scroll(to: model, at: .none, animated: true)
}
//MARK: -
public func view(for element: Any) -> UIView? {
guard let realElement = element as? Model else { return nil }
return self.view(for: realElement) as? UIView
}
public func view(for model: Model) -> ContentCell? {
guard let index = self.index(of: model) else { return nil }
let indexPath = IndexPath(row: index, section: 0)
return self.delegate?.dequeu(at: indexPath)
}
}
|
2eccedb3df5a63d40ef591945a7e3512
| 30.516484 | 81 | 0.604951 | false | false | false | false |
AngryLi/ResourceSummary
|
refs/heads/master
|
iOS/Demos/Assignments_swift/assignment-final/01-sqlite测试/01-sqlite测试/Main/class/Header/LsDBOperator.swift
|
mit
|
3
|
//
// LsDBOperator.swift
// 01-sqlite测试
//
// Created by 李亚洲 on 15/6/9.
// Copyright © 2015年 angryli. All rights reserved.
//
import UIKit
class LsDBOperator: NSObject
{
private let DBName = "test.db"
private let TableName = "users"
func getDB() -> FMDatabase
{
let fileMgr = NSFileManager.defaultManager()
let docsDir = NSSearchPathForDirectoriesInDomains( .DocumentDirectory , .UserDomainMask, true)[0] as! String
let databasePath = docsDir.stringByAppendingPathComponent(DBName)
if !fileMgr.fileExistsAtPath(databasePath)
{
let db = FMDatabase(path: databasePath)
if db == nil
{
print("创建数据库失败:\(db.lastErrorMessage())")
print(databasePath, appendNewline: true)
}
else
{
print("创建数据库成功")
}
}
let myDB = FMDatabase(path: databasePath)
if !myDB.tableExists(TableName)
{
if myDB.open()
{
let sql_stmt = "CREATE TABLE \(TableName) (user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, name TEXT NOT NULL DEFAULT 老婆,icon BLOB)"
if !myDB.executeStatements(sql_stmt)
{
print("创建失败: \(myDB.lastErrorMessage())")
}
myDB.close()
}
else
{
print("打开数据库失败: \(myDB.lastErrorMessage())")
}
}
return myDB
}
func getAllUser() -> [LsUser]
{
var userArray = [LsUser]()
let db = getDB()
db.open()
if let result = db.executeQuery("select * from \(TableName)", withArgumentsInArray: [])
{
if result.next()
{
let user = LsUser(newName:NSString(data: result.dataForColumn("name"), encoding: NSUTF8StringEncoding) as! String , newIcon:UIImage(data: result.dataForColumn("icon"))!)
userArray.append(user)
}
}
db.close()
return userArray
}
func insert(user : LsUser) ->Bool
{
let db = getDB()
db.open()
if db.executeUpdate("insert into \(TableName)(name,icon) values (?,?)", withArgumentsInArray:[user.name!.dataUsingEncoding(NSUTF8StringEncoding)!,UIImagePNGRepresentation(user.iconImage!)!])
{
print("插入数据成功", appendNewline: true)
db.close()
return true
}
else
{
print("插入数据失败" + db.lastErrorMessage(), appendNewline: true)
db.close()
return false
}
}
func clearDB() -> Bool
{
let db = getDB()
db.open()
//println(db)
if db.executeStatements("delete from \(TableName)")
{
print("清理数据库成功", appendNewline: true)
db.close()
return true
}
else
{
print("清除数据库失败", appendNewline: true)
db.close()
return false
}
}
func dropTable(tableName : String) -> Bool
{
let db = getDB()
db.open()
if db.executeStatements("drop table \(tableName)")
{
print("删除数据库<\(tableName)>成功", appendNewline: true)
db.close()
return true
}
else
{
print("删除数据库<\(tableName)>失败", appendNewline: true)
db.close()
return false
}
}
}
|
c200154cb0cf0a7b2712884448c9719e
| 27.782258 | 198 | 0.505464 | false | false | false | false |
marty-suzuki/HoverConversion
|
refs/heads/master
|
HoverConversionSample/HoverConversionSample/ViewController/UserTimelineViewController.swift
|
mit
|
1
|
//
// UserTimelineViewController.swift
// HoverConversionSample
//
// Created by Taiki Suzuki on 2016/09/05.
// Copyright © 2016年 marty-suzuki. All rights reserved.
//
import UIKit
import HoverConversion
import TwitterKit
class UserTimelineViewController: HCContentViewController {
var user: TWTRUser?
fileprivate var tweets: [TWTRTweet] = []
fileprivate var hasNext = true
fileprivate let client = TWTRAPIClient()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationView.backgroundColor = UIColor(red: 85 / 255, green: 172 / 255, blue: 238 / 255, alpha: 1)
if let user = user {
navigationView.titleLabel.numberOfLines = 2
let attributedText = NSMutableAttributedString()
attributedText.append(NSAttributedString(string: user.name + "\n", attributes: [
NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14),
NSForegroundColorAttributeName : UIColor.white
]))
attributedText.append(NSAttributedString(string: "@" + user.screenName, attributes: [
NSFontAttributeName : UIFont.systemFont(ofSize: 12),
NSForegroundColorAttributeName : UIColor(white: 1, alpha: 0.6)
]))
navigationView.titleLabel.attributedText = attributedText
}
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
tableView.register(TWTRTweetTableViewCell.self, forCellReuseIdentifier: "TWTRTweetTableViewCell")
tableView.dataSource = self
loadTweets()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func loadTweets() {
guard let user = user , hasNext else { return }
let oldestTweetId = tweets.first?.tweetID
let request = StatusesUserTimelineRequest(screenName: user.screenName, maxId: oldestTweetId, count: nil)
client.sendTwitterRequest(request) { [weak self] in
switch $0.result {
case .success(let tweets):
if tweets.count < 1 {
self?.hasNext = false
return
}
let filterdTweets = tweets.filter { $0.tweetID != oldestTweetId }
let sortedTweets = filterdTweets.sorted { $0.0.createdAt.timeIntervalSince1970 < $0.1.createdAt.timeIntervalSince1970 }
guard let storedTweets = self?.tweets else { return }
self?.tweets = sortedTweets + storedTweets
self?.tableView.reloadData()
if let tweets = self?.tweets {
let indexPath = IndexPath(row: tweets.count - 2, section: 0)
self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
case .failure(let error):
print(error)
self?.hasNext = false
}
}
}
}
extension UserTimelineViewController {
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat {
guard (indexPath as NSIndexPath).row < tweets.count else { return 0 }
let tweet = tweets[(indexPath as NSIndexPath).row]
let width = UIScreen.main.bounds.size.width
return TWTRTweetTableViewCell.height(for: tweet, style: .compact, width: width, showingActions: false)
}
func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) {
if (indexPath as NSIndexPath).row < 1 {
//loadTweets()
}
}
}
extension UserTimelineViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TWTRTweetTableViewCell") as? TWTRTweetTableViewCell else {
return tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")!
}
cell.configure(with: tweets[(indexPath as NSIndexPath).row])
return cell
}
}
|
0f32c4637e5dd84a3f8320c7cb7f5d7a
| 40.458716 | 135 | 0.642841 | false | false | false | false |
mownier/photostream
|
refs/heads/master
|
Photostream/Modules/User Activity/Interactor/UserActivityData.swift
|
mit
|
1
|
//
// UserActivityData.swift
// Photostream
//
// Created by Mounir Ybanez on 22/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
protocol UserActivityData {
var timestamp: Double { set get }
var userId: String { set get }
var avatarUrl: String { set get }
var displayName: String { set get }
}
protocol UserActivityLikeData: UserActivityData {
var photoUrl: String { set get }
var postId: String { set get }
}
protocol UserActivityPostData: UserActivityData {
var photoUrl: String { set get }
var postId: String { set get }
}
protocol UserActivityCommentData: UserActivityData {
var commentId: String { set get }
var message: String { set get }
var photoUrl: String { set get }
var postId: String { set get }
}
protocol UserActivityFollowData: UserActivityData {
var isFollowing: Bool { set get }
}
struct UserActivityLikeDataItem: UserActivityLikeData {
var timestamp: Double = 0
var userId: String = ""
var avatarUrl: String = ""
var displayName: String = ""
var photoUrl: String = ""
var postId: String = ""
init(user: User, post: Post) {
userId = user.id
avatarUrl = user.avatarUrl
displayName = user.displayName
photoUrl = post.photo.url
postId = post.id
}
}
struct UserActivityPostDataItem: UserActivityLikeData {
var timestamp: Double = 0
var userId: String = ""
var avatarUrl: String = ""
var displayName: String = ""
var photoUrl: String = ""
var postId: String = ""
init(user: User, post: Post) {
userId = user.id
avatarUrl = user.avatarUrl
displayName = user.displayName
photoUrl = post.photo.url
postId = post.id
}
}
struct UserActivityCommentDataItem: UserActivityCommentData {
var timestamp: Double = 0
var userId: String = ""
var avatarUrl: String = ""
var displayName: String = ""
var commentId: String = ""
var message: String = ""
var photoUrl: String = ""
var postId: String = ""
init(user: User, comment: Comment, post: Post) {
userId = user.id
avatarUrl = user.avatarUrl
displayName = user.displayName
commentId = comment.id
message = comment.message
photoUrl = post.photo.url
postId = post.id
}
}
struct UserActivityFollowDataItem: UserActivityFollowData {
var timestamp: Double = 0
var userId: String = ""
var avatarUrl: String = ""
var displayName: String = ""
var isFollowing: Bool = false
init(user: User) {
userId = user.id
avatarUrl = user.avatarUrl
displayName = user.displayName
}
}
|
fd552aaa0c266a214d91fe4388a6accb
| 21.069767 | 61 | 0.603793 | false | false | false | false |
gregomni/swift
|
refs/heads/main
|
stdlib/public/Concurrency/AsyncFlatMapSequence.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Creates an asynchronous sequence that concatenates the results of calling
/// the given transformation with each element of this sequence.
///
/// Use this method to receive a single-level asynchronous sequence when your
/// transformation produces an asynchronous sequence for each element.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `5`. The transforming closure takes the received `Int`
/// and returns a new `Counter` that counts that high. For example, when the
/// transform receives `3` from the base sequence, it creates a new `Counter`
/// that produces the values `1`, `2`, and `3`. The `flatMap(_:)` method
/// "flattens" the resulting sequence-of-sequences into a single
/// `AsyncSequence`.
///
/// let stream = Counter(howHigh: 5)
/// .flatMap { Counter(howHigh: $0) }
/// for await number in stream {
/// print("\(number)", terminator: " ")
/// }
/// // Prints: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
///
/// - Parameter transform: A mapping closure. `transform` accepts an element
/// of this sequence as its parameter and returns an `AsyncSequence`.
/// - Returns: A single, flattened asynchronous sequence that contains all
/// elements in all the asychronous sequences produced by `transform`.
@preconcurrency
@inlinable
public __consuming func flatMap<SegmentOfResult: AsyncSequence>(
_ transform: @Sendable @escaping (Element) async -> SegmentOfResult
) -> AsyncFlatMapSequence<Self, SegmentOfResult> {
return AsyncFlatMapSequence(self, transform: transform)
}
}
/// An asynchronous sequence that concatenates the results of calling a given
/// transformation with each element of this sequence.
@available(SwiftStdlib 5.1, *)
public struct AsyncFlatMapSequence<Base: AsyncSequence, SegmentOfResult: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let transform: (Base.Element) async -> SegmentOfResult
@usableFromInline
init(
_ base: Base,
transform: @escaping (Base.Element) async -> SegmentOfResult
) {
self.base = base
self.transform = transform
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncFlatMapSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The flat map sequence produces the type of element in the asynchronous
/// sequence produced by the `transform` closure.
public typealias Element = SegmentOfResult.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the flat map sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let transform: (Base.Element) async -> SegmentOfResult
@usableFromInline
var currentIterator: SegmentOfResult.AsyncIterator?
@usableFromInline
var finished = false
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
transform: @escaping (Base.Element) async -> SegmentOfResult
) {
self.baseIterator = baseIterator
self.transform = transform
}
/// Produces the next element in the flat map sequence.
///
/// This iterator calls `next()` on its base iterator; if this call returns
/// `nil`, `next()` returns `nil`. Otherwise, `next()` calls the
/// transforming closure on the received element, takes the resulting
/// asynchronous sequence, and creates an asynchronous iterator from it.
/// `next()` then consumes values from this iterator until it terminates.
/// At this point, `next()` is ready to receive the next value from the base
/// sequence.
@inlinable
public mutating func next() async rethrows -> SegmentOfResult.Element? {
while !finished {
if var iterator = currentIterator {
do {
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
// restore the iterator since we just mutated it with next
currentIterator = iterator
return element
} catch {
finished = true
throw error
}
} else {
guard let item = try await baseIterator.next() else {
finished = true
return nil
}
do {
let segment = await transform(item)
var iterator = segment.makeAsyncIterator()
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
currentIterator = iterator
return element
} catch {
finished = true
throw error
}
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), transform: transform)
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncFlatMapSequence: @unchecked Sendable
where Base: Sendable,
Base.Element: Sendable,
SegmentOfResult: Sendable,
SegmentOfResult.Element: Sendable { }
@available(SwiftStdlib 5.1, *)
extension AsyncFlatMapSequence.Iterator: @unchecked Sendable
where Base.AsyncIterator: Sendable,
Base.Element: Sendable,
SegmentOfResult: Sendable,
SegmentOfResult.Element: Sendable,
SegmentOfResult.AsyncIterator: Sendable { }
|
5b5d462020a35478a497e9c42c9ae5f6
| 34.97093 | 89 | 0.647972 | false | false | false | false |
iCrany/iOSExample
|
refs/heads/master
|
iOSExample/Module/TransitionExample/ViewController/Session4/Present/PresentAnotherToViewController.swift
|
mit
|
1
|
//
// PresentAnotherToViewController.swift
// iOSExample
//
// Created by iCrany on 2017/12/9.
// Copyright © 2017 iCrany. All rights reserved.
//
import Foundation
import UIKit
class PresentAnotherToViewController: UIViewController {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(nibName: nil, bundle: nil)
self.setupUI()
}
private func setupUI() {
self.view.backgroundColor = .blue
let titleLabel = UILabel()
titleLabel.text = "这里是 PushToAnotherViewController"
self.view.addSubview(titleLabel)
titleLabel.backgroundColor = .black
titleLabel.textColor = .white
titleLabel.snp.makeConstraints { maker in
maker.center.equalToSuperview()
maker.size.equalTo(CGSize(width: 200, height: 60))
}
}
}
|
3fe6973c01ba351a73d8ec36909ffbe1
| 24.942857 | 62 | 0.648678 | false | false | false | false |
tardieu/swift
|
refs/heads/master
|
test/SILGen/generic_witness.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3foo{{[_0-9a-zA-Z]*}}F : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Runcible }
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015generic_witness6CanvasVyxGAA6MediumAaA3InkRzAA3Pen5PaintRpzlAaDP4drawy7Texture_AGQZ5paint_qd__6penciltAA6PencilRd__AL6StrokeRtd__lFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
// CHECK: [[FN:%.*]] = function_ref @_T015generic_witness6CanvasV4drawy5PaintQz5paint_qd__6penciltAA6PencilRd__6StrokeQyd__AFRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
|
b7e596ab7664878a0a91ab1ed50210da
| 42.464286 | 369 | 0.628184 | false | false | false | false |
hovansuit/FoodAndFitness
|
refs/heads/master
|
FoodAndFitness/Controllers/UserExercisesDetail/UserExercisesDetailController.swift
|
mit
|
1
|
//
// UserExercisesDetailController.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/18/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import SwiftUtils
final class UserExercisesDetailController: BaseViewController {
@IBOutlet fileprivate(set) weak var tableView: TableView!
var viewModel: UserExercisesDetailViewModel!
override var isNavigationBarHidden: Bool {
return true
}
enum Sections: Int {
case userExercises
case information
case suggestion
static var count: Int {
return self.suggestion.hashValue + 1
}
var title: String {
switch self {
case .userExercises:
return Strings.empty
case .information:
return Strings.informationExercise
case .suggestion:
return Strings.suggestionExercise
}
}
var heightForHeader: CGFloat {
switch self {
case .userExercises:
return 224
default:
return 70
}
}
}
enum InformationRows: Int {
case calories
case duration
static var count: Int {
return self.duration.rawValue + 1
}
var title: String {
switch self {
case .calories:
return Strings.calories
case .duration:
return Strings.duration
}
}
}
override func setupUI() {
super.setupUI()
configureTableView()
configureViewModel()
}
private func configureTableView() {
tableView.register(AddUserFoodCell.self)
tableView.register(UserFoodCell.self)
tableView.register(InfomationNutritionCell.self)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
private func configureViewModel() {
viewModel.delegate = self
}
}
// MARK: - UserExercisesDetailViewModelDelegate
extension UserExercisesDetailController: UserExercisesDetailViewModelDelegate {
func viewModel(_ viewModel: UserExercisesDetailViewModel, needsPerformAction action: UserExercisesDetailViewModel.Action) {
switch action {
case .userExercisesChanged:
tableView.reloadData()
}
}
}
// MARK: - UITableViewDataSource
extension UserExercisesDetailController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return Sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userExercises:
return viewModel.userExercises.count + 1
case .information:
return InformationRows.count
case .suggestion:
return viewModel.suggestExercises.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userExercises:
switch indexPath.row {
case 0:
let cell = tableView.dequeue(AddUserFoodCell.self)
cell.data = viewModel.dataForAddButton()
cell.delegate = self
return cell
default:
let cell = tableView.dequeue(UserFoodCell.self)
cell.accessoryType = .none
cell.data = viewModel.dataForUserExercise(at: indexPath.row - 1)
return cell
}
case .information:
guard let rows = InformationRows(rawValue: indexPath.row) else {
fatalError(Strings.Errors.enumError)
}
let cell = tableView.dequeue(InfomationNutritionCell.self)
cell.data = viewModel.dataForInformationExercise(at: rows)
return cell
case .suggestion:
let cell = tableView.dequeue(UserFoodCell.self)
cell.accessoryType = .disclosureIndicator
cell.data = viewModel.dataForSuggestExercise(at: indexPath.row)
return cell
}
}
}
// MARK: - UITableViewDelegate
extension UserExercisesDetailController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userExercises: break
case .information: break
case .suggestion:
let exercises = viewModel.suggestExercises
guard indexPath.row >= 0, indexPath.row < exercises.count else { break }
let exerciseDetailController = ExerciseDetailController()
exerciseDetailController.viewModel = ExerciseDetailViewModel(exercise: exercises[indexPath.row], activity: viewModel.activity)
navigationController?.pushViewController(exerciseDetailController, animated: true)
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userExercises:
return true
case .information, .suggestion:
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .delete:
viewModel.delete(at: indexPath.row - 1, completion: { (result) in
switch result {
case .success(_):
tableView.deleteRows(at: [indexPath], with: .automatic)
case .failure(let error):
error.show()
}
})
default: break
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
return sections.heightForHeader
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let sections = Sections(rawValue: indexPath.section) else {
fatalError(Strings.Errors.enumError)
}
if sections == .userExercises && indexPath.row == 0 { return 60 }
return 55
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
if sections == .userExercises && viewModel.userExercises.isEmpty {
return .leastNormalMagnitude
} else {
return 10
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sections = Sections(rawValue: section) else {
fatalError(Strings.Errors.enumError)
}
switch sections {
case .userExercises:
let headerView: MealHeaderView = MealHeaderView.loadNib()
headerView.delegate = self
headerView.data = viewModel.dataForHeaderView()
return headerView
default:
let headerView: TitleCell = TitleCell.loadNib()
headerView.data = TitleCell.Data(title: sections.title)
return headerView.contentView
}
}
}
// MARK: - MealHeaderViewDelegate
extension UserExercisesDetailController: MealHeaderViewDelegate {
func view(_ view: MealHeaderView, needsPerformAction action: MealHeaderView.Action) {
back(view.backButton)
}
}
// MARK: - AddUserFoodCellDelegate
extension UserExercisesDetailController: AddUserFoodCellDelegate {
func cell(_ cell: AddUserFoodCell, needsPerformAction action: AddUserFoodCell.Action) {
switch action {
case .add:
let addActivityController = AddActivityController()
addActivityController.viewModel = AddActivityViewModel(activity: viewModel.activity)
navigationController?.pushViewController(addActivityController, animated: true)
}
}
}
|
0927f56d1d8f1c23d71b960753ff1021
| 32.484615 | 138 | 0.623248 | false | false | false | false |
remobjects/Marzipan
|
refs/heads/master
|
CodeGen4/CGCStyleCodeGenerator.swift
|
bsd-3-clause
|
1
|
//
// Abstract base implementation for all C-style languages (C#, Obj-C, Swift, Java, C++)
//
public __abstract class CGCStyleCodeGenerator : CGCodeGenerator {
override public init() {
useTabs = true
tabSize = 4
}
func wellKnownSymbolForCustomOperator(name: String!) -> String? {
switch name.ToUpper() {
case "plus": return "+"
case "minus": return "-"
case "bitwisenot": return "!"
case "increment": return "++"
case "decrement": return "--"
//case "implicit": return "__implicit"
//case "explicit": return "__explicit"
case "true": return "true"
case "false": return "false"
case "add": return "+"
case "subtract": return "-"
case "multiply": return "*"
case "divide": return "/"
case "modulus": return "%"
case "bitwiseand": return "&"
case "bitwiseor": return "|"
case "bitwisexor": return "^"
case "shiftlft": return "<<"
case "shiftright": return ">>"
case "equal": return "="
case "notequal": return "<>"
case "less": return "<"
case "lessorequal": return "<="
case "greater": return ">"
case "greaterorequal": return ">="
case "in": return "in"
default: return nil
}
}
override func generateInlineComment(_ comment: String) {
var comment = comment.Replace("*/", "* /")
Append("/* \(comment) */")
}
override func generateConditionStart(_ condition: CGConditionalDefine) {
if let name = condition.Expression as? CGNamedIdentifierExpression {
Append("#ifdef ")
Append(name.Name)
} else {
//if let not = statement.Condition.Expression as? CGUnaryOperatorExpression, not.Operator == .Not,
if let not = condition.Expression as? CGUnaryOperatorExpression, not.Operator == CGUnaryOperatorKind.Not,
let name = not.Value as? CGNamedIdentifierExpression {
Append("#ifndef ")
Append(name.Name)
} else {
Append("#if ")
generateExpression(condition.Expression)
}
}
// generateConditionalDefine(condition)
AppendLine()
}
override func generateConditionElse() {
AppendLine("#else")
}
override func generateConditionEnd(_ condition: CGConditionalDefine) {
AppendLine("#endif")
}
override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) {
AppendLine("{")
incIndent()
generateStatements(statement.Statements)
decIndent()
AppendLine("}")
}
override func generateIfElseStatement(_ statement: CGIfThenElseStatement) {
Append("if (")
generateExpression(statement.Condition)
AppendLine(")")
generateStatementIndentedUnlessItsABeginEndBlock(statement.IfStatement)
if let elseStatement = statement.ElseStatement {
AppendLine("else")
generateStatementIndentedUnlessItsABeginEndBlock(elseStatement)
}
}
override func generateForToLoopStatement(_ statement: CGForToLoopStatement) {
Append("for (")
if let type = statement.LoopVariableType {
generateTypeReference(type)
Append(" ")
}
generateIdentifier(statement.LoopVariableName)
Append(" = ")
generateExpression(statement.StartValue)
Append("; ")
generateIdentifier(statement.LoopVariableName)
if statement.Direction == CGLoopDirectionKind.Forward {
Append(" <= ")
} else {
Append(" >= ")
}
generateExpression(statement.EndValue)
Append("; ")
generateIdentifier(statement.LoopVariableName)
if statement.Direction == CGLoopDirectionKind.Forward {
Append("++ ")
} else {
Append("-- ")
}
AppendLine(")")
generateStatementIndentedUnlessItsABeginEndBlock(statement.NestedStatement)
}
override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) {
Append("while (")
generateExpression(statement.Condition)
AppendLine(")")
generateStatementIndentedUnlessItsABeginEndBlock(statement.NestedStatement)
}
override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) {
AppendLine("do")
AppendLine("{")
incIndent()
generateStatementsSkippingOuterBeginEndBlock(statement.Statements)
decIndent()
AppendLine("}")
Append("while (")
generateExpression(statement.Condition)
AppendLine(");")
}
override func generateSwitchStatement(_ statement: CGSwitchStatement) {
Append("switch (")
generateExpression(statement.Expression)
AppendLine(")")
AppendLine("{")
incIndent()
for c in statement.Cases {
for e in c.CaseExpressions {
Append("case ")
generateExpression(e)
AppendLine(":")
}
generateStatementsIndentedUnlessItsASingleBeginEndBlock(c.Statements)
}
if let defaultStatements = statement.DefaultCase, defaultStatements.Count > 0 {
AppendLine("default:")
generateStatementsIndentedUnlessItsASingleBeginEndBlock(defaultStatements)
}
decIndent()
AppendLine("}")
}
override func generateReturnStatement(_ statement: CGReturnStatement) {
if let value = statement.Value {
Append("return ")
generateExpression(value)
generateStatementTerminator()
} else {
Append("return")
generateStatementTerminator()
}
}
override func generateBreakStatement(_ statement: CGBreakStatement) {
Append("break")
generateStatementTerminator()
}
override func generateContinueStatement(_ statement: CGContinueStatement) {
Append("continue")
generateStatementTerminator()
}
override func generateAssignmentStatement(_ statement: CGAssignmentStatement) {
generateExpression(statement.Target)
Append(" = ")
generateExpression(statement.Value)
generateStatementTerminator()
}
override func generateGotoStatement(_ statement: CGGotoStatement) {
Append("goto ");
Append(statement.Target);
generateStatementTerminator();
}
override func generateLabelStatement(_ statement: CGLabelStatement) {
Append(statement.Name);
Append(":");
generateStatementTerminator();
}
//
// Expressions
//
override func generateSizeOfExpression(_ expression: CGSizeOfExpression) {
Append("sizeof(")
generateExpression(expression.Expression)
Append(")")
}
override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) {
Append("(*(")
generateExpression(expression.PointerExpression)
Append("))")
}
override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) {
switch (`operator`) {
case .Plus: Append("+")
case .Minus: Append("-")
case .Not: Append("!")
case .BitwiseNot: Append("~")
case .AddressOf: Append("&")
case .ForceUnwrapNullable: // no-op
}
}
override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) {
switch (`operator`) {
case .Concat: fallthrough
case .Addition: Append("+")
case .Subtraction: Append("-")
case .Multiplication: Append("*")
case .Division: Append("/")
case .LegacyPascalDivision: Append("/") // not really supported in C-Style
case .Modulus: Append("%")
case .Equals: Append("==")
case .NotEquals: Append("!=")
case .LessThan: Append("<")
case .LessThanOrEquals: Append("<=")
case .GreaterThan: Append(">")
case .GreatThanOrEqual: Append(">=")
case .LogicalAnd: Append("&&")
case .LogicalOr: Append("||")
case .LogicalXor: Append("^^")
case .Shl: Append("<<")
case .Shr: Append(">>")
case .BitwiseAnd: Append("&")
case .BitwiseOr: Append("|")
case .BitwiseXor: Append("^")
//case .Implies:
case .Is: Append("is")
//case .IsNot:
//case .In:
//case .NotIn:
case .Assign: Append("=")
case .AssignAddition: Append("+=")
case .AssignSubtraction: Append("-=")
case .AssignMultiplication: Append("*=")
case .AssignDivision: Append("/=")
default: Append("/* NOT SUPPORTED */") /* Oxygene only */
}
}
override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) {
Append("(")
generateExpression(expression.Condition)
Append(" ? ")
generateExpression(expression.IfExpression)
if let elseExpression = expression.ElseExpression {
Append(" : ")
generateExpression(elseExpression)
}
Append(")")
}
internal func cStyleEscapeCharactersInStringLiteral(_ string: String) -> String {
let result = StringBuilder()
let len = length(string)
for i in 0 ..< len {
let ch = string[i]
switch ch {
case "\0": result.Append("\\0")
case "\\": result.Append("\\\\")
case "\'": result.Append("\\'")
case "\"": result.Append("\\\"")
//case "\b": result.Append("\\b") // swift doesn't do \b
case "\t": result.Append("\\t")
case "\r": result.Append("\\r")
case "\n": result.Append("\\n")
/*
case "\0".."\31": result.Append("\\"+Integer(ch).ToString()) // Cannot use the binary operator ".."
case "\u{0080}".."\u{ffffffff}": result.Append("\\u{"+Sugar.Cryptography.Utils.ToHexString(Integer(ch), 4)) // Cannot use the binary operator ".."
*/
default:
if ch < 32 || ch > 0x7f {
result.Append(cStyleEscapeSequenceForCharacter(ch))
} else {
result.Append(ch)
}
}
}
return result.ToString()
}
internal func cStyleEscapeSequenceForCharacter(_ ch: Char) -> String {
return "\\U"+Convert.ToHexString(Integer(ch), 8) // plain C: always use 8 hex digits with "\U"
}
override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) {
Append("\"\(cStyleEscapeCharactersInStringLiteral(expression.Value))\"")
}
override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) {
Append("'\(cStyleEscapeCharactersInStringLiteral(expression.Value.ToString()))'")
}
private func cStyleAppendNumberKind(_ numberKind: CGNumberKind?) {
if let numberKind = numberKind {
switch numberKind {
case .Unsigned: Append("U")
case .Long: Append("L")
case .UnsignedLong: Append("UL")
case .Float: Append("F")
case .Double: Append("D")
case .Decimal: Append("M")
}
}
}
override func generateIntegerLiteralExpression(_ literalExpression: CGIntegerLiteralExpression) {
switch literalExpression.Base {
case 16: Append("0x"+literalExpression.StringRepresentation(base:16))
case 10: Append(literalExpression.StringRepresentation(base:10))
case 8: Append("0"+literalExpression.StringRepresentation(base:8))
default: throw Exception("Base \(literalExpression.Base) integer literals are not currently supported for C-Style languages.")
}
cStyleAppendNumberKind(literalExpression.NumberKind)
}
override func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) {
switch literalExpression.Base {
case 10: Append(literalExpression.StringRepresentation())
default: throw Exception("Base \(literalExpression.Base) integer literals are not currently supported for C-Style languages.")
}
cStyleAppendNumberKind(literalExpression.NumberKind)
}
override func generatePointerTypeReference(_ type: CGPointerTypeReference) {
generateTypeReference(type.`Type`)
Append("*")
}
}
|
a5b8830df282477045891e4206e2e088
| 28.947222 | 150 | 0.699443 | false | false | false | false |
socrata/soda-swift
|
refs/heads/main
|
SODAKit/SODAClient.swift
|
apache-2.0
|
1
|
//
// SODAClient.swift
// SODAKit
//
// Created by Frank A. Krueger on 8/9/14.
// Copyright (c) 2014 Socrata, Inc. All rights reserved.
//
import Foundation
// Reference: http://dev.socrata.com/consumers/getting-started.html
/// The default number of items to return in SODAClient.queryDataset calls.
public let SODADefaultLimit = 1000
/// The result of an asynchronous SODAClient.queryDataset call. It can either succeed with data or fail with an error.
public enum SODADatasetResult {
case dataset ([[String: Any]])
case error (Error)
}
/// The result of an asynchronous SODAClient.getRow call. It can either succeed with data or fail with an error.
public enum SODARowResult {
case row ([String: Any])
case error (Error)
}
/// Callback for asynchronous queryDataset methods of SODAClient
public typealias SODADatasetCompletionHandler = (SODADatasetResult) -> Void
/// Callback for asynchronous getRow method of SODAClient
public typealias SODARowCompletionHandler = (SODARowResult) -> Void
/// Consumes data from a Socrata OpenData end point.
public class SODAClient {
public let domain: String
public let token: String
/// Initializes this client to communicate with a SODA endpoint.
public init(domain: String, token: String) {
self.domain = domain
self.token = token
}
/// Gets a row using its identifier. See http://dev.socrata.com/docs/row-identifiers.html
public func get(row: String, inDataset: String, _ completionHandler: @escaping SODARowCompletionHandler) {
get(dataset: "\(inDataset)/\(row)", withParameters: [:]) { res in
switch res {
case .dataset (let rows):
completionHandler(.row (rows[0]))
case .error(let err):
completionHandler(.error (err))
}
}
}
/// Asynchronously gets a dataset using a simple filter query. See http://dev.socrata.com/docs/filtering.html
public func get(dataset: String, withFilters: [String: String], limit: Int = SODADefaultLimit, offset: Int = 0, _ completionHandler: @escaping SODADatasetCompletionHandler) {
var ps = withFilters
ps["$limit"] = "\(limit)"
ps["$offset"] = "\(offset)"
get(dataset: dataset, withParameters: ps, completionHandler)
}
/// Low-level access for asynchronously getting a dataset. You should use SODAQueries instead of this. See http://dev.socrata.com/docs/queries.html
public func get(dataset: String, withParameters: [String: String], _ completionHandler: @escaping SODADatasetCompletionHandler) {
// Get the URL
let query = SODAClient.paramsToQueryString (withParameters)
let path = dataset.hasPrefix("/") ? dataset : ("/resource/" + dataset)
let url = "https://\(self.domain)\(path).json?\(query)"
let urlToSend = URL(string: url)
// Build the request
let request = NSMutableURLRequest(url: urlToSend!)
request.addValue("application/json", forHTTPHeaderField:"Accept")
request.addValue(self.token, forHTTPHeaderField:"X-App-Token")
// Send it
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, reqError in
// We sync the callback with the main thread to make UI programming easier
let syncCompletion = { res in OperationQueue.main.addOperation { completionHandler (res) } }
// Give up if there was a net error
if let error = reqError {
syncCompletion(.error (error))
return
}
// Try to parse the JSON
// println(NSString (data: data, encoding: NSUTF8StringEncoding))
var jsonError: Error?
var jsonResult: Any!
do {
jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
} catch let error {
jsonError = error
jsonResult = nil
}
if let error = jsonError {
syncCompletion(.error (error))
return
}
// Interpret the JSON
if let array = jsonResult as? [[String: Any]] {
syncCompletion(.dataset (array))
}
else if let dict = jsonResult as? [String: Any] {
if let _ = dict["error"], let errorMessage = dict["message"] {
syncCompletion(.error (NSError(domain: "SODA", code: 0, userInfo: ["Error": errorMessage])))
return
}
syncCompletion(.dataset ([dict]))
}
else {
if let error = reqError {
syncCompletion(.error (error))
}
}
}
task.resume()
}
/// Converts an NSDictionary into a query string.
fileprivate class func paramsToQueryString (_ params: [String: String]) -> String {
var s = ""
var head = ""
for (key, value) in params {
let sk = key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let sv = value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
s += head+sk!+"="+sv!
head = "&"
}
return s
}
}
/// SODAQuery extension to SODAClient
public extension SODAClient {
/// Get a query object that can be used to query the client using a fluent syntax.
func query(dataset: String) -> SODAQuery {
return SODAQuery (client: self, dataset: dataset)
}
}
/// Assists in the construction of a SoQL query.
public class SODAQuery
{
public let client: SODAClient
public let dataset: String
public let parameters: [String: String]
/// Initializes all the parameters of the query
public init(client: SODAClient, dataset: String, parameters: [String: String] = [:])
{
self.client = client
self.dataset = dataset
self.parameters = parameters
}
/// Generates SoQL $select parameter. Use the AS operator to modify the output.
public func select(_ select: String) -> SODAQuery {
var ps = self.parameters
ps["$select"] = select
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $where parameter. Use comparison operators and AND, OR, NOT, IS NULL, IS NOT NULL. Strings must be single-quoted.
public func filter(_ filter: String) -> SODAQuery {
var ps = self.parameters
ps["$where"] = filter
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates simple filter parameter. Multiple filterColumns are allowed in a single query.
public func filterColumn(_ column: String, _ value: String) -> SODAQuery {
var ps = self.parameters
ps[column] = value
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $q parameter. This uses a multi-column full text search.
public func fullText(_ fullText: String) -> SODAQuery {
var ps = self.parameters
ps["$q"] = fullText
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $order ASC parameter.
public func orderAscending(_ column: String) -> SODAQuery {
var ps = self.parameters
ps["$order"] = "\(column) ASC"
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $order DESC parameter.
public func orderDescending(_ column: String) -> SODAQuery {
var ps = self.parameters
ps["$order"] = "\(column) DESC"
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $group parameter. Use select() with aggregation functions like MAX and then name the column to group by.
public func group(_ column: String) -> SODAQuery {
var ps = self.parameters
ps["$group"] = column
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $limit parameter. The default limit is 1000.
public func limit(_ limit: Int) -> SODAQuery {
var ps = self.parameters
ps["$limit"] = "\(limit)"
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Generates SoQL $offset parameter.
public func offset(_ offset: Int) -> SODAQuery {
var ps = self.parameters
ps["$offset"] = "\(offset)"
return SODAQuery (client: self.client, dataset: self.dataset, parameters: ps)
}
/// Performs the query asynchronously and sends all the results to the completion handler.
public func get(_ completionHandler: @escaping (SODADatasetResult) -> Void) {
client.get(dataset: dataset, withParameters: parameters, completionHandler)
}
/// Performs the query asynchronously and sends the results, one row at a time, to an iterator function.
public func each(_ iterator: @escaping (SODARowResult) -> Void) {
client.get(dataset: dataset, withParameters: parameters) { res in
switch res {
case .dataset (let data):
for row in data {
iterator(.row (row))
}
case .error (let err):
iterator(.error (err))
}
}
}
}
|
e4856d81a80f476c54e36c43d98edbbb
| 37.764 | 178 | 0.6149 | false | false | false | false |
ninewine/SaturnTimer
|
refs/heads/master
|
SaturnTimer/Model/STTimerNotification.swift
|
mit
|
1
|
//
// STTimerNotification.swift
// SaturnTimer
//
// Created by Tidy Nine on 3/10/16.
// Copyright © 2016 Tidy Nine. All rights reserved.
//
import UIKit
import AVFoundation
class STTimerNotification: NSObject {
internal class var shareInstance: STTimerNotification {
struct Static {
static let instance: STTimerNotification = STTimerNotification()
}
return Static.instance
}
var audioPlayer: AVAudioPlayer?
func showNotificationWithLocalNotification(_ notification: UILocalNotification) {
showNotification(notification.alertBody)
playSoundWithNotification(notification)
}
func showNotificationWithString (_ alertBody: String?) {
showNotification(alertBody)
}
func playSoundWithFileName (_ fileName: String) {
let soundFileComponents = fileName.components(separatedBy: CharacterSet(charactersIn: "."))
if soundFileComponents.count > 1 {
if let url = Bundle.main.url(forResource: soundFileComponents[0], withExtension: soundFileComponents[1]) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: soundFileComponents[1])
audioPlayer?.play()
}
catch {
}
}
}
}
fileprivate func showNotification (_ alertBody: String?) {
let alert = RCAlertView(title: nil, message: alertBody, image: nil)
alert.addButtonWithTitle(HelperLocalization.Done, type: .fill, handler: {[weak self] _ in
self?.audioPlayer?.stop()
})
alert.show()
}
fileprivate func playSoundWithNotification (_ notification: UILocalNotification) {
if let fireDate = notification.fireDate {
if Date().timeIntervalSince(fireDate) < 0.5 {
if let soundFileName = notification.soundName, soundFileName != UILocalNotificationDefaultSoundName {
playSoundWithFileName(soundFileName)
}
}
}
}
}
|
97d661cc218ea49972990ababe41a918
| 28.873016 | 112 | 0.695537 | false | false | false | false |
rvald/Wynfood.iOS
|
refs/heads/main
|
Wynfood/CreateReviewViewController.swift
|
apache-2.0
|
1
|
//
// CreateReviewViewController.swift
// Wynfood
//
// Created by craftman on 5/18/17.
// Copyright © 2017 craftman. All rights reserved.
//
import UIKit
let didPostReviewNotification = Notification.Name("WynfoodDidPostReviewNotification")
class CreateReviewViewController: UIViewController, UITextViewDelegate{
// MARK: - Properties
private var buttons = [UIButton]()
var networkingService = NetworkingService()
let authService = AuthenticationService()
var restaurantId = 0
var restaurantName = ""
var userId = ""
var rating = 0 {
didSet {
updateButtonSelectionStates()
}
}
// MARK: - View Cycle
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 243.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, alpha: 1.0)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(screenTap)))
nameLabel.text = restaurantName
setupViews()
}
// MARK: - Views
let closeButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Close", for: .normal)
button.addTarget(self, action: #selector(closeButtonTap), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Wynwood Bar"
label.font = UIFont.preferredFont(forTextStyle: .title1)
label.textColor = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var textView: UITextView = {
let view = UITextView()
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 5.0
view.font = UIFont.preferredFont(forTextStyle: .body)
view.delegate = self
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let postButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Post Review", for: .normal)
button.addTarget(self, action: #selector(postReview), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
// MARK: - Methods
func screenTap() {
if textView.isFirstResponder {
textView.resignFirstResponder()
}
}
func postReview() {
if textView.isFirstResponder {
textView.resignFirstResponder()
}
if rating == 0 || textView.text.characters.count < 3 {
let alertController = UIAlertController(title: "Wynfood", message: "Invalid rating or review.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
} else {
let rating = Rating(userName: authService.getUserName(), restaurantId: restaurantId, text: textView.text, value: self.rating, created: nil)
networkingService.postRating(rating: rating)
let alertController = UIAlertController(title: "Wynfood", message: "We appreciate your feedback.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: { (action) in
self.dismiss(animated: true, completion: nil)
})
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
}
func closeButtonTap() {
dismiss(animated: true, completion: nil)
}
private func createRatingButtons() {
for index in 0..<5 {
let button = UIButton()
button.setImage(UIImage(named: "star_empty_lg"), for: .normal)
button.setImage(UIImage(named: "star_fill_lg"), for: .selected)
button.setImage(UIImage(named: "star_fill_lg"), for: [.highlighted, .selected])
button.adjustsImageWhenHighlighted = false
button.tag = index
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchDown)
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button)
buttons.append(button)
}
}
private func updateButtonSelectionStates() {
for (index, button) in buttons.enumerated() {
button.isSelected = index < rating
}
}
@objc private func ratingButtonTapped(button: UIButton) {
rating = button.tag + 1
updateButtonSelectionStates()
}
private func addContraintsToRatingButtons(ratingButtons: [UIButton]) {
for (index, button) in ratingButtons.enumerated() {
if index == 0 {
let width = view.frame.size.width
if width > 375 {
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-70-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": button]))
} else {
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": button]))
}
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-12-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": button, "v1": nameLabel]))
} else {
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v1]-12-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": button, "v1": ratingButtons[button.tag - 1]]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-12-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": button, "v1": nameLabel]))
}
}
}
func setupViews() {
view.addSubview(closeButton)
view.addSubview(nameLabel)
createRatingButtons()
view.addSubview(textView)
view.addSubview(postButton)
// close button constraints
view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 40.0))
view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0))
// name label constraints
view.addConstraint(NSLayoutConstraint(item: nameLabel, attribute: .top, relatedBy: .equal, toItem: closeButton, attribute: .bottom, multiplier: 1.0, constant: 48.0))
view.addConstraint(NSLayoutConstraint(item: nameLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 1.0))
// textview constraints
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": textView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-24-[v0(100)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": textView, "v1": buttons[0]]))
// post buttom constraints
view.addConstraint(NSLayoutConstraint(item: postButton, attribute: .top, relatedBy: .equal, toItem: textView, attribute: .bottom, multiplier: 1.0, constant: 13.0))
view.addConstraint(NSLayoutConstraint(item: postButton, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 1.0))
addContraintsToRatingButtons(ratingButtons: buttons)
}
// MARK: - TextView
func textViewDidEndEditing(_ textView: UITextView) {
textView.resignFirstResponder()
}
}
|
4c699b6de7553ce979e12bd8a1b838fb
| 35.307054 | 211 | 0.591657 | false | false | false | false |
Jnosh/swift
|
refs/heads/master
|
test/Parse/ConditionalCompilation/decl_in_true_inactive.swift
|
apache-2.0
|
38
|
// RUN: %target-typecheck-verify-swift -D FOO -D BAR
// SR-3996 Incorrect type checking when using defines
// Decls in true-but-inactive blocks used to be leaked.
func f1() -> Int {
#if FOO
let val = 1
#elseif BAR
let val = 2
#endif
return val
}
func f2() -> Int {
#if FOO
#elseif BAR
let val = 3
#endif
return val // expected-error {{use of unresolved identifier 'val'}}
}
struct S1 {
#if FOO
let val = 1
#elseif BAR
let val = 2
#endif
var v: Int {
return val
}
}
struct S2 {
#if FOO
#elseif BAR
let val = 2
#endif
var v: Int {
return val // expected-error {{use of unresolved identifier 'val'}}
}
}
#if FOO
let gVal1 = 1
#elseif BAR
let gVal2 = 2
#endif
_ = gVal1
#if FOO
#elseif BAR
let inactive = 3
#endif
_ = inactive // expected-error {{use of unresolved identifier 'inactive'}}
|
93b1c97fb9ee32faa19dbc70e491aa2e
| 14.240741 | 74 | 0.647631 | false | false | false | false |
AnnMic/FestivalArchitect
|
refs/heads/master
|
EntitasSwift/FestivalArchitect/Classes/TileMapNode.swift
|
mit
|
1
|
//
// TileMapNode.swift
// Festival
//
// Created by Ann Michelsen on 28/09/14.
// Copyright (c) 2014 Ann Michelsen. All rights reserved.
//
import Foundation
class TileMapNode : CCNode {
var dragDropSprite :CCSprite!
var dragDropFileName :String!
let tileMap:CCTiledMap!
let background:CCTiledMapLayer!
var metaLayer:CCTiledMapLayer!
var foregroundLayer:CCTiledMapLayer!
var npcLayer:CCTiledMapLayer!
var panningPosition : CGPoint!
let spawnPoint:CGPoint!
let winSize:CGRect!
override init()
{
super.init()
tileMap = CCTiledMap(file: "TileMap.tmx")
tileMap.position = CGPointMake(0, 0)
addChild(tileMap, z: -1)
winSize = CCDirector.sharedDirector().view.frame
panningPosition = CGPointMake(0, 0)
metaLayer = tileMap.layerNamed("Meta")
metaLayer.visible = false;
background = tileMap.layerNamed("Background")
foregroundLayer = tileMap.layerNamed("Foreground")
npcLayer = tileMap.layerNamed("npc")
var objectGroup:CCTiledMapObjectGroup = tileMap.objectGroupNamed("Objects")
var spawnPointDict : NSDictionary = objectGroup.objectNamed("SpawnPoint")
var x : CGFloat = spawnPointDict["x"] as CGFloat
var y : CGFloat = spawnPointDict["y"] as CGFloat
spawnPoint = CGPointMake(x, y)
addObservers()
}
func addObservers(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "addDragSprite:", name:AJAddTileToTileMap, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "addSpriteToTileMap:", name:AJConfirmTileToBeAdded, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "removeDragSprite:", name:AJCancelTileToBeAdded, object: nil)
}
override func onExit()
{
super.onExit()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func addDragSprite(notification:NSNotification){
let userInfo = notification.userInfo as Dictionary<String,String!>
let messageString:String = userInfo["message"]!
dragDropFileName = messageString + ".png"
dragDropSprite = CCSprite(imageNamed: dragDropFileName)
dragDropSprite.position = CGPointMake(winSize.width/2-panningPosition.x, winSize.height/2-panningPosition.y)
addChild(dragDropSprite)
}
func removeDragSprite(sender:AnyObject){
removeChild(dragDropSprite)
}
func addSpriteToTileMap(sender:AnyObject){
var sprite:CCSprite = CCSprite(imageNamed: dragDropFileName)
sprite.position = dragDropSprite.position
removeChild(dragDropSprite)
addChild(sprite)
}
/*
code to add the sprite to the actual tilemap
var panningPos = getPositionInTileMap(sprite.position)
var positionInTileMap = tileCoordForPosition(panningPos)
background.removeTileAt(positionInTileMap)
background.setTileGID(150, at: positionInTileMap)
removeChild(sprite)*/
func getPositionInTileMap(position : CGPoint) -> CGPoint{
var x = position.x - panningPosition.x
var y = position.y - panningPosition.y
var newPos : CGPoint = CGPointMake(x, y)
return newPos
}
func tileCoordForPosition(position:CGPoint) -> CGPoint{
var x: Int = Int(position.x) / Int(tileMap.tileSize.width)
var y: Int = Int((tileMap.mapSize.height * tileMap.tileSize.height) - position.y) / Int(tileMap.tileSize.height);
return CGPointMake(CGFloat(x), CGFloat(y))
}
func positionForTileCoord(tileCoord:CGPoint) -> CGPoint{
var x:CGFloat = (tileCoord.x * tileMap.tileSize.width) + tileMap.tileSize.width;
var y:CGFloat = (tileMap.mapSize.height * tileMap.tileSize.height) - (tileCoord.y * tileMap.tileSize.height) - tileMap.tileSize.height;
return CGPointMake(x, y)
}
}
|
666e9ccfe787802c6148040c896c1f52
| 32.889831 | 143 | 0.677339 | false | false | false | false |
esttorhe/RxSwift
|
refs/heads/feature/swift2.0
|
RxBlocking/RxBlocking/Observable+Blocking.swift
|
mit
|
1
|
//
// Observable+Blocking.swift
// RxBlocking
//
// Created by Krunoslav Zaher on 7/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
public func toArray<E>(source: Observable<E>)
-> RxResult<[E]> {
let condition = NSCondition()
var elements = [E]()
var error: ErrorType?
var ended = false
source.subscribeSafe(AnonymousObserver { e in
switch e {
case .Next(let element):
elements.append(element)
case .Error(let e):
error = e
condition.lock()
ended = true
condition.signal()
condition.unlock()
case .Completed:
condition.lock()
ended = true
condition.signal()
condition.unlock()
}
})
condition.lock()
while !ended {
condition.wait()
}
condition.unlock()
if let error = error {
return failure(error)
}
return success(elements)
}
public func first<E>(source: Observable<E>)
-> RxResult<E?> {
let condition = NSCondition()
var element: E?
var error: ErrorType?
var ended = false
let d = SingleAssignmentDisposable()
d.disposable = source.subscribeSafe(AnonymousObserver { e in
switch e {
case .Next(let e):
if element == nil {
element = e
}
break
case .Error(let e):
error = e
default:
break
}
condition.lock()
ended = true
condition.signal()
condition.unlock()
})
condition.lock()
while !ended {
condition.wait()
}
d.dispose()
condition.unlock()
if let error = error {
return failure(error)
}
return success(element)
}
public func last<E>(source: Observable<E>)
-> RxResult<E?> {
let condition = NSCondition()
var element: E?
var error: ErrorType?
var ended = false
let d = SingleAssignmentDisposable()
d.disposable = source.subscribeSafe(AnonymousObserver { e in
switch e {
case .Next(let e):
element = e
return
case .Error(let e):
error = e
default:
break
}
condition.lock()
ended = true
condition.signal()
condition.unlock()
})
condition.lock()
while !ended {
condition.wait()
}
d.dispose()
condition.unlock()
if let error = error {
return failure(error)
}
return success(element)
}
|
e658dcf53fc5053b8b4144d31f4ecc42
| 18.811594 | 64 | 0.515917 | false | false | false | false |
mauriciopf/iOS-six-week-technical-challenge
|
refs/heads/master
|
challenge_dev_Mauricio/challenge_dev_Mauricio/RandomVC.swift
|
mit
|
1
|
//
// RandomVC.swift
// challenge_dev_Mauricio
//
// Created by mauriciopf on 8/12/15.
// Copyright (c) 2015 mauriciopf. All rights reserved.
//
import UIKit
import CoreData
class RandomVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var mtableView: UITableView!
var mArray = [NSManagedObject]()
var pairArray = [NSManagedObject]()
var oddArray = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
for element in mArray {
let index = find(mArray, element)
if index! % 2 == 0 {
pairArray.append(element)
} else {
oddArray.append(element)
}
}
println(DataController.sharedInstance.newStudents)
view.backgroundColor = UIColor.whiteColor()
mtableView = UITableView(frame: self.view.frame)
mtableView.delegate = self
mtableView.registerClass(randomTableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
mtableView.dataSource = self
view.addSubview(mtableView)
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return oddArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! randomTableViewCell
cell.studentLabel1.text = pairArray[indexPath.row].valueForKey("name") as? String
cell.studentLabel2.text = oddArray[indexPath.row].valueForKey("name") as? String
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
d218462933771be9d0c3cea8bffa8bda
| 24.06422 | 119 | 0.58858 | false | false | false | false |
SanctionCo/pilot-ios
|
refs/heads/master
|
Pods/Gallery/Sources/Utils/Extensions/AVAsset+Extensions.swift
|
mit
|
1
|
import UIKit
import AVFoundation
extension AVAsset {
fileprivate var g_naturalSize: CGSize {
return tracks(withMediaType: AVMediaType.video).first?.naturalSize ?? .zero
}
var g_correctSize: CGSize {
return g_isPortrait ? CGSize(width: g_naturalSize.height, height: g_naturalSize.width) : g_naturalSize
}
var g_isPortrait: Bool {
let portraits: [UIInterfaceOrientation] = [.portrait, .portraitUpsideDown]
return portraits.contains(g_orientation)
}
var g_fileSize: Double {
guard let avURLAsset = self as? AVURLAsset else { return 0 }
var result: AnyObject?
try? (avURLAsset.url as NSURL).getResourceValue(&result, forKey: URLResourceKey.fileSizeKey)
if let result = result as? NSNumber {
return result.doubleValue
} else {
return 0
}
}
var g_frameRate: Float {
return tracks(withMediaType: AVMediaType.video).first?.nominalFrameRate ?? 30
}
// Same as UIImageOrientation
var g_orientation: UIInterfaceOrientation {
guard let transform = tracks(withMediaType: AVMediaType.video).first?.preferredTransform else {
return .portrait
}
switch (transform.tx, transform.ty) {
case (0, 0):
return .landscapeRight
case (g_naturalSize.width, g_naturalSize.height):
return .landscapeLeft
case (0, g_naturalSize.width):
return .portraitUpsideDown
default:
return .portrait
}
}
// MARK: - Description
var g_videoDescription: CMFormatDescription? {
guard let object = tracks(withMediaType: AVMediaType.video).first?.formatDescriptions.first else {
return nil
}
return (object as! CMFormatDescription)
}
var g_audioDescription: CMFormatDescription? {
guard let object = tracks(withMediaType: AVMediaType.audio).first?.formatDescriptions.first else {
return nil
}
return (object as! CMFormatDescription)
}
}
|
1b33c9c6a244170df0d53f63d9f23dcc
| 25.690141 | 106 | 0.699208 | false | false | false | false |
amoriello/trust-line-ios
|
refs/heads/develop
|
Trustline/BleManager.swift
|
mit
|
1
|
//
// BleManager.swift
// Trustline
//
// Created by matt on 10/10/2015.
// Copyright © 2015 amoriello.hutti. All rights reserved.
//
import Foundation
import CoreBluetooth
let g_tokenServiceCBUUID = CBUUID(string:"713D0000-503E-4C75-BA94-3148F18D941E")
let g_tokenReadCharacteristicUUID = CBUUID(string:"713D0002-503E-4C75-BA94-3148F18D941E")
let g_tokenWriteCharacteristicUUID = CBUUID(string:"713D0003-503E-4C75-BA94-3148F18D941E")
//----------------------------------------------------------------------------------------
class BleManager: NSObject, CBCentralManagerDelegate {
typealias DiscoverHandler = ([Token], NSError?) -> (Void)
typealias ConnectToPairedTokenHander = (Token?, NSError?) -> (Void)
typealias ManagerStateErrorHandler = (NSError?) -> (Void)
var centralManager :CBCentralManager!
var tokens :[Token] = []
var managerStateErrorHandler: ManagerStateErrorHandler
var discoverHandler: DiscoverHandler?
var pairedTokens: Set<CDPairedToken>?
var discoveredPaired = false
var tokenServiceCBUUID = g_tokenServiceCBUUID
init(managerStateErrorHandler: ManagerStateErrorHandler) {
self.managerStateErrorHandler = managerStateErrorHandler
}
func discoverTokens(pairedTokens :Set<CDPairedToken>? = nil, completion: DiscoverHandler) {
print("initializing central manager");
discoverHandler = completion
self.pairedTokens = pairedTokens
if centralManager == nil {
print("Creating central manager")
centralManager = CBCentralManager(delegate:self, queue:nil)
} else {
tokens = []
centralManager.scanForPeripheralsWithServices([tokenServiceCBUUID], options: nil)
}
NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "scanTimeout:", userInfo: nil, repeats: false)
}
func notify(error: NSError) {
if let _ = discoverHandler {
discoverHandler!([], error)
discoverHandler = nil
}
managerStateErrorHandler(error);
}
func centralManagerDidUpdateState(central: CBCentralManager) {
print("central manager updated state");
switch (central.state) {
case .PoweredOff:
notify(createError("Bluetooth", description: "Hardware is powered off"));
case .Resetting:
notify(createError("Bluetooth", description: "Hardware is resetting"));
case .Unauthorized:
notify(createError("Bluetooth", description: "State is unauthorized"))
case .Unknown:
notify(createError("Bluetooth", description: "State is unknown"))
case .Unsupported:
notify(createError("Bluetooth", description: "Hardware is unsupported on this platform"))
case .PoweredOn:
if discoverHandler != nil {
centralManager.scanForPeripheralsWithServices([tokenServiceCBUUID], options: nil)
} else {
print("No discoverHandler")
}
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print("Discovered \(peripheral.name), RSSI: \(RSSI) UUID: \(peripheral.identifier.UUIDString)")
if pairedTokens != nil {
for pairedToken in pairedTokens! {
if peripheral.identifier == pairedToken.identifier {
if let km = KeyMaterial.getFromUUID(peripheral.identifier) {
let token = Token(centralManager: centralManager, peripheral: peripheral, identifier: peripheral.identifier, keyMaterial: km, connectionStateHandler: managerStateErrorHandler)
discoveredPaired = true;
discoverHandler!([token], nil)
centralManager.stopScan()
return
}
}
}
}
tokens.append(Token(centralManager: centralManager, peripheral: peripheral,
identifier: peripheral.identifier,
connectionStateHandler: managerStateErrorHandler))
}
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
managerStateErrorHandler(error);
}
func scanTimeout(timer: NSTimer) {
if !discoveredPaired {
centralManager.stopScan()
// discoverHandler normaly set to nil in notify function
if discoverHandler != nil {
discoverHandler!(tokens, nil)
}
}
// Re-initialize value
discoveredPaired = false
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
print("Connected to \(peripheral.name)")
peripheral.discoverServices(nil)
}
}
|
1a69209da447578836d29090fc4bafc1
| 33.059259 | 187 | 0.684863 | false | false | false | false |
anzfactory/TwitterClientCLI
|
refs/heads/master
|
Sources/TwitterClientCore/Model/RateLimit.swift
|
mit
|
1
|
//
// RateLimit.swift
// TwitterClientCLIPackageDescription
//
// Created by shingo asato on 2017/10/09.
//
import Foundation
import APIKit
import Rainbow
struct RateLimit: Outputable {
enum Path {
case homeTimeline, userTimeline, tweet, retweet, search, favorites
var string: String {
switch self {
case .homeTimeline:
return "/statuses/home_timeline"
case .userTimeline:
return "/statuses/user_timeline"
case .tweet:
return "/statuses/show/:id"
case .retweet:
return "/statuses/retweets/:id"
case .search:
return "/search/tweets"
case .favorites:
return "/favorites/list"
}
}
var name: String {
switch self {
case .homeTimeline:
return "タイムライン"
case .userTimeline:
return "ユーザタイムライン"
case .tweet:
return "ツイート詳細"
case .retweet:
return "リツイート"
case .search:
return "ツイート検索"
case .favorites:
return "いいねリスト"
}
}
}
var list: [Path: RateLimitState] = [Path: RateLimitState]()
init(_ object: Any) throws {
guard let dictionary = object as? [String: Any], let resources = dictionary["resources"] as? [String: Any] else {
throw ResponseError.unexpectedObject("unknown...")
}
if let statuses = resources["statuses"] as? [String: Any] {
if let obj = statuses[Path.homeTimeline.string], let state = RateLimitState(obj) {
self.list[.homeTimeline] = state
}
if let obj = statuses[Path.userTimeline.string], let state = RateLimitState(obj) {
self.list[.userTimeline] = state
}
if let obj = statuses[Path.tweet.string], let state = RateLimitState(obj) {
self.list[.tweet] = state
}
if let obj = statuses[Path.retweet.string], let state = RateLimitState(obj) {
self.list[.retweet] = state
}
}
if let search = resources["search"] as? [String: Any] {
if let obj = search[Path.search.string], let state = RateLimitState(obj) {
self.list[.search] = state
}
}
if let favorites = resources["favorites"] as? [String: Any] {
if let obj = favorites[Path.favorites.string], let state = RateLimitState(obj) {
self.list[.favorites] = state
}
}
}
func output() -> String {
var body = [String]()
for (key, state) in self.list {
body.append("\(key.name.bold) (\(key.string.underline))\n\(state.output())")
}
return body.joined(separator: "\n")
}
}
struct RateLimitState: Outputable {
let limit: Int
let remaining: Int
let resetTimestamp: Int
init?(_ object: Any) {
guard let obj = object as? [String: Any] else {
return nil
}
self.limit = obj["limit"] as? Int ?? 0
self.remaining = obj["remaining"] as? Int ?? 0
self.resetTimestamp = obj["reset"] as? Int ?? 0
}
func output() -> String {
let delta = self.resetTimestamp - Int(Date().timeIntervalSince1970)
return "制限: \(self.limit)times/15min\n" +
"残り: \(self.remaining)times\n" +
"リセットまで: \(delta)sec\n"
}
}
|
0c7f066fca91c5a771efaf62da66bd2f
| 29.5 | 121 | 0.513388 | false | false | false | false |
KaiCode2/swift-corelibs-foundation
|
refs/heads/master
|
Foundation/NSScanner.swift
|
apache-2.0
|
3
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public class NSScanner : NSObject, NSCopying {
internal var _scanString: String
internal var _skipSet: NSCharacterSet?
internal var _invertedSkipSet: NSCharacterSet?
internal var _scanLocation: Int
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(_ zone: NSZone) -> AnyObject {
return NSScanner(string: string)
}
public var string: String {
return _scanString
}
public var scanLocation: Int {
get {
return _scanLocation
}
set {
if newValue > string.length {
fatalError("Index \(newValue) beyond bounds; string length \(string.length)")
}
_scanLocation = newValue
}
}
/*@NSCopying*/ public var charactersToBeSkipped: NSCharacterSet? {
get {
return _skipSet
}
set {
_skipSet = newValue?.copy() as? NSCharacterSet
_invertedSkipSet = nil
}
}
internal var invertedSkipSet: NSCharacterSet? {
if let inverted = _invertedSkipSet {
return inverted
} else {
if let set = charactersToBeSkipped {
_invertedSkipSet = set.inverted
return _invertedSkipSet
}
return nil
}
}
public var caseSensitive: Bool = false
public var locale: NSLocale?
internal static let defaultSkipSet = NSCharacterSet.whitespacesAndNewlines()
public init(string: String) {
_scanString = string
_skipSet = NSScanner.defaultSkipSet
_scanLocation = 0
}
}
internal struct _NSStringBuffer {
var bufferLen: Int
var bufferLoc: Int
var string: NSString
var stringLen: Int
var _stringLoc: Int
var buffer = Array<unichar>(repeating: 0, count: 32)
var curChar: unichar?
static let EndCharacter = unichar(0xffff)
init(string: String, start: Int, end: Int) {
self.string = string._bridgeToObject()
_stringLoc = start
stringLen = end
if _stringLoc < stringLen {
bufferLen = min(32, stringLen - _stringLoc)
let range = NSMakeRange(_stringLoc, bufferLen)
bufferLoc = 1
buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in
self.string.getCharacters(ptr.baseAddress!, range: range)
})
curChar = buffer[0]
} else {
bufferLen = 0
bufferLoc = 1
curChar = _NSStringBuffer.EndCharacter
}
}
init(string: NSString, start: Int, end: Int) {
self.string = string
_stringLoc = start
stringLen = end
if _stringLoc < stringLen {
bufferLen = min(32, stringLen - _stringLoc)
let range = NSMakeRange(_stringLoc, bufferLen)
bufferLoc = 1
buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in
self.string.getCharacters(ptr.baseAddress!, range: range)
})
curChar = buffer[0]
} else {
bufferLen = 0
bufferLoc = 1
curChar = _NSStringBuffer.EndCharacter
}
}
var currentCharacter: unichar {
return curChar!
}
var isAtEnd: Bool {
return curChar == _NSStringBuffer.EndCharacter
}
mutating func fill() {
bufferLen = min(32, stringLen - _stringLoc)
let range = NSMakeRange(_stringLoc, bufferLen)
buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in
string.getCharacters(ptr.baseAddress!, range: range)
})
bufferLoc = 1
curChar = buffer[0]
}
mutating func advance() {
if bufferLoc < bufferLen { /*buffer is OK*/
curChar = buffer[bufferLoc]
bufferLoc += 1
} else if (_stringLoc + bufferLen < stringLen) { /* Buffer is empty but can be filled */
_stringLoc += bufferLen
fill()
} else { /* Buffer is empty and we're at the end */
bufferLoc = bufferLen + 1
curChar = _NSStringBuffer.EndCharacter
}
}
mutating func rewind() {
if bufferLoc > 1 { /* Buffer is OK */
bufferLoc -= 1
curChar = buffer[bufferLoc - 1]
} else if _stringLoc > 0 { /* Buffer is empty but can be filled */
bufferLoc = min(32, _stringLoc)
bufferLen = bufferLoc
_stringLoc -= bufferLen
let range = NSMakeRange(_stringLoc, bufferLen)
buffer.withUnsafeMutableBufferPointer({ (ptr: inout UnsafeMutableBufferPointer<unichar>) -> Void in
string.getCharacters(ptr.baseAddress!, range: range)
})
} else {
bufferLoc = 0
curChar = _NSStringBuffer.EndCharacter
}
}
mutating func skip(_ skipSet: NSCharacterSet?) {
if let set = skipSet {
while set.characterIsMember(currentCharacter) && !isAtEnd {
advance()
}
}
}
var location: Int {
get {
return _stringLoc + bufferLoc - 1
}
mutating set {
if newValue < _stringLoc || newValue >= _stringLoc + bufferLen {
if newValue < 16 { /* Get the first NSStringBufferSize chars */
_stringLoc = 0
} else if newValue > stringLen - 16 { /* Get the last NSStringBufferSize chars */
_stringLoc = stringLen < 32 ? 0 : stringLen - 32
} else {
_stringLoc = newValue - 16 /* Center around loc */
}
fill()
}
bufferLoc = newValue - _stringLoc
curChar = buffer[bufferLoc]
bufferLoc += 1
}
}
}
private func isADigit(_ ch: unichar) -> Bool {
struct Local {
static let set = NSCharacterSet.decimalDigits()
}
return Local.set.characterIsMember(ch)
}
// This is just here to allow just enough generic math to handle what is needed for scanning an abstract integer from a string, perhaps these should be on IntegerType?
internal protocol _BitShiftable {
func >>(lhs: Self, rhs: Self) -> Self
func <<(lhs: Self, rhs: Self) -> Self
}
internal protocol _IntegerLike : Integer, _BitShiftable {
init(_ value: Int)
static var max: Self { get }
static var min: Self { get }
}
internal protocol _FloatArithmeticType {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
internal protocol _FloatLike : FloatingPoint, _FloatArithmeticType {
init(_ value: Int)
init(_ value: Double)
static var max: Self { get }
static var min: Self { get }
}
extension Int : _IntegerLike { }
extension Int32 : _IntegerLike { }
extension Int64 : _IntegerLike { }
extension UInt32 : _IntegerLike { }
extension UInt64 : _IntegerLike { }
// these might be good to have in the stdlib
extension Float : _FloatLike {
static var max: Float { return FLT_MAX }
static var min: Float { return FLT_MIN }
}
extension Double : _FloatLike {
static var max: Double { return DBL_MAX }
static var min: Double { return DBL_MIN }
}
private func numericValue(_ ch: unichar) -> Int {
if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) {
return Int(ch) - Int(unichar(unicodeScalarLiteral: "0"))
} else {
return __CFCharDigitValue(UniChar(ch))
}
}
private func numericOrHexValue(_ ch: unichar) -> Int {
if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) {
return Int(ch) - Int(unichar(unicodeScalarLiteral: "0"))
} else if (ch >= unichar(unicodeScalarLiteral: "A") && ch <= unichar(unicodeScalarLiteral: "F")) {
return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "A"))
} else if (ch >= unichar(unicodeScalarLiteral: "a") && ch <= unichar(unicodeScalarLiteral: "f")) {
return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "a"))
} else {
return -1
}
}
private func decimalSep(_ locale: NSLocale?) -> String {
if let loc = locale {
if let sep = loc.objectForKey(NSLocaleDecimalSeparator) as? NSString {
return sep._swiftObject
}
return "."
} else {
return decimalSep(NSLocale.currentLocale())
}
}
extension String {
internal func scan<T: _IntegerLike>(_ skipSet: NSCharacterSet?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool {
var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length)
buf.skip(skipSet)
var neg = false
var localResult: T = 0
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-")
buf.advance()
buf.skip(skipSet)
}
if (!isADigit(buf.currentCharacter)) {
return false
}
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
if (localResult >= T.max / 10) && ((localResult > T.max / 10) || T(numeral - (neg ? 1 : 0)) >= T.max - localResult * 10) {
// apply the clamps and advance past the ending of the buffer where there are still digits
localResult = neg ? T.min : T.max
neg = false
repeat {
buf.advance()
} while (isADigit(buf.currentCharacter))
break
} else {
// normal case for scanning
localResult = localResult * 10 + T(numeral)
}
buf.advance()
} while (isADigit(buf.currentCharacter))
to(neg ? -1 * localResult : localResult)
locationToScanFrom = buf.location
return true
}
internal func scanHex<T: _IntegerLike>(_ skipSet: NSCharacterSet?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool {
var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length)
buf.skip(skipSet)
var localResult: T = 0
var curDigit: Int
if buf.currentCharacter == unichar(unicodeScalarLiteral: "0") {
buf.advance()
let locRewindTo = buf.location
curDigit = numericOrHexValue(buf.currentCharacter)
if curDigit == -1 {
if buf.currentCharacter == unichar(unicodeScalarLiteral: "x") || buf.currentCharacter == unichar(unicodeScalarLiteral: "X") {
buf.advance()
curDigit = numericOrHexValue(buf.currentCharacter)
}
}
if curDigit == -1 {
locationToScanFrom = locRewindTo
to(T(0))
return true
}
} else {
curDigit = numericOrHexValue(buf.currentCharacter)
if curDigit == -1 {
return false
}
}
repeat {
if localResult > T.max >> T(4) {
localResult = T.max
} else {
localResult = (localResult << T(4)) + T(curDigit)
}
buf.advance()
curDigit = numericOrHexValue(buf.currentCharacter)
} while (curDigit != -1)
to(localResult)
locationToScanFrom = buf.location
return true
}
internal func scan<T: _FloatLike>(_ skipSet: NSCharacterSet?, locale: NSLocale?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool {
let ds_chars = decimalSep(locale).utf16
let ds = ds_chars[ds_chars.startIndex]
var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length)
buf.skip(skipSet)
var neg = false
var localResult: T = T(0)
if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") {
neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-")
buf.advance()
buf.skip(skipSet)
}
if (!isADigit(buf.currentCharacter)) {
return false
}
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
// if (localResult >= T.max / T(10)) && ((localResult > T.max / T(10)) || T(numericValue(buf.currentCharacter) - (neg ? 1 : 0)) >= T.max - localResult * T(10)) is evidently too complex; so break it down to more "edible chunks"
let limit1 = localResult >= T.max / T(10)
let limit2 = localResult > T.max / T(10)
let limit3 = T(numeral - (neg ? 1 : 0)) >= T.max - localResult * T(10)
if (limit1) && (limit2 || limit3) {
// apply the clamps and advance past the ending of the buffer where there are still digits
localResult = neg ? T.min : T.max
neg = false
repeat {
buf.advance()
} while (isADigit(buf.currentCharacter))
break
} else {
localResult = localResult * T(10) + T(numeral)
}
buf.advance()
} while (isADigit(buf.currentCharacter))
if buf.currentCharacter == ds {
var factor = T(0.1)
buf.advance()
repeat {
let numeral = numericValue(buf.currentCharacter)
if numeral == -1 {
break
}
localResult = localResult + T(numeral) * factor
factor = factor * T(0.1)
buf.advance()
} while (isADigit(buf.currentCharacter))
}
to(neg ? T(-1) * localResult : localResult)
locationToScanFrom = buf.location
return true
}
internal func scanHex<T: _FloatLike>(_ skipSet: NSCharacterSet?, locale: NSLocale?, locationToScanFrom: inout Int, to: (T) -> Void) -> Bool {
NSUnimplemented()
}
}
extension NSScanner {
// On overflow, the below methods will return success and clamp
public func scanInt(_ result: UnsafeMutablePointer<Int32>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: Int32) -> Void in
result.pointee = value
}
}
public func scanInteger(_ result: UnsafeMutablePointer<Int>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: Int) -> Void in
result.pointee = value
}
}
public func scanLongLong(_ result: UnsafeMutablePointer<Int64>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: Int64) -> Void in
result.pointee = value
}
}
public func scanUnsignedLongLong(_ result: UnsafeMutablePointer<UInt64>) -> Bool {
return _scanString.scan(_skipSet, locationToScanFrom: &_scanLocation) { (value: UInt64) -> Void in
result.pointee = value
}
}
public func scanFloat(_ result: UnsafeMutablePointer<Float>) -> Bool {
return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Float) -> Void in
result.pointee = value
}
}
public func scanDouble(_ result: UnsafeMutablePointer<Double>) -> Bool {
return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Double) -> Void in
result.pointee = value
}
}
public func scanHexInt(_ result: UnsafeMutablePointer<UInt32>) -> Bool {
return _scanString.scanHex(_skipSet, locationToScanFrom: &_scanLocation) { (value: UInt32) -> Void in
result.pointee = value
}
}
public func scanHexLongLong(_ result: UnsafeMutablePointer<UInt64>) -> Bool {
return _scanString.scanHex(_skipSet, locationToScanFrom: &_scanLocation) { (value: UInt64) -> Void in
result.pointee = value
}
}
public func scanHexFloat(_ result: UnsafeMutablePointer<Float>) -> Bool {
return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Float) -> Void in
result.pointee = value
}
}
public func scanHexDouble(_ result: UnsafeMutablePointer<Double>) -> Bool {
return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &_scanLocation) { (value: Double) -> Void in
result.pointee = value
}
}
public var atEnd: Bool {
var stringLoc = scanLocation
let stringLen = string.length
if let invSet = invertedSkipSet {
let range = string._nsObject.rangeOfCharacter(from: invSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
return stringLoc == stringLen
}
public class func localizedScannerWithString(_ string: String) -> AnyObject { NSUnimplemented() }
}
/// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer and better Optional usage.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
extension NSScanner {
public func scanInt() -> Int32? {
var value: Int32 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int32>) -> Int32? in
if scanInt(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanInteger() -> Int? {
var value: Int = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int>) -> Int? in
if scanInteger(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanLongLong() -> Int64? {
var value: Int64 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int64>) -> Int64? in
if scanLongLong(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanUnsignedLongLong() -> UInt64? {
var value: UInt64 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in
if scanUnsignedLongLong(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanFloat() -> Float? {
var value: Float = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in
if scanFloat(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanDouble() -> Double? {
var value: Double = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in
if scanDouble(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanHexInt() -> UInt32? {
var value: UInt32 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt32>) -> UInt32? in
if scanHexInt(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanHexLongLong() -> UInt64? {
var value: UInt64 = 0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in
if scanHexLongLong(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanHexFloat() -> Float? {
var value: Float = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in
if scanHexFloat(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
public func scanHexDouble() -> Double? {
var value: Double = 0.0
return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in
if scanHexDouble(ptr) {
return ptr.pointee
} else {
return nil
}
}
}
// These methods avoid calling the private API for _invertedSkipSet and manually re-construct them so that it is only usage of public API usage
// Future implementations on Darwin of these methods will likely be more optimized to take advantage of the cached values.
public func scanString(string searchString: String) -> String? {
let str = self.string._bridgeToObject()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = [caseSensitive ? [] : NSStringCompareOptions.caseInsensitiveSearch, NSStringCompareOptions.anchoredSearch]
if let invSkipSet = charactersToBeSkipped?.inverted {
let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
let range = str.range(of: searchString, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length > 0 {
/* ??? Is the range below simply range? 99.9% of the time, and perhaps even 100% of the time... Hmm... */
let res = str.substring(with: NSMakeRange(stringLoc, range.location + range.length - stringLoc))
scanLocation = range.location + range.length
return res
}
return nil
}
public func scanCharactersFromSet(_ set: NSCharacterSet) -> String? {
let str = self.string._bridgeToObject()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.caseInsensitiveSearch
if let invSkipSet = charactersToBeSkipped?.inverted {
let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
var range = str.rangeOfCharacter(from: set.inverted, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length == 0 {
range.location = stringLen
}
if stringLoc != range.location {
let res = str.substring(with: NSMakeRange(stringLoc, range.location - stringLoc))
scanLocation = range.location
return res
}
return nil
}
public func scanUpToString(_ string: String) -> String? {
let str = self.string._bridgeToObject()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.caseInsensitiveSearch
if let invSkipSet = charactersToBeSkipped?.inverted {
let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
var range = str.range(of: string, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length == 0 {
range.location = stringLen
}
if stringLoc != range.location {
let res = str.substring(with: NSMakeRange(stringLoc, range.location - stringLoc))
scanLocation = range.location
return res
}
return nil
}
public func scanUpToCharactersFromSet(_ set: NSCharacterSet) -> String? {
let str = self.string._bridgeToObject()
var stringLoc = scanLocation
let stringLen = str.length
let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.caseInsensitiveSearch
if let invSkipSet = charactersToBeSkipped?.inverted {
let range = str.rangeOfCharacter(from: invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc))
stringLoc = range.length > 0 ? range.location : stringLen
}
var range = str.rangeOfCharacter(from: set, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc))
if range.length == 0 {
range.location = stringLen
}
if stringLoc != range.location {
let res = str.substring(with: NSMakeRange(stringLoc, range.location - stringLoc))
scanLocation = range.location
return res
}
return nil
}
}
|
0ec981eb838ea390a45de3bb3ba6ea66
| 35.821127 | 239 | 0.577822 | false | false | false | false |
DianQK/Flix
|
refs/heads/master
|
Flix/Builder/AnimatableTableViewBuilder.swift
|
mit
|
1
|
//
// AnimatableTableViewBuilder.swift
// Flix
//
// Created by DianQK on 04/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
public class AnimatableTableViewBuilder: _TableViewBuilder, PerformGroupUpdatesable {
typealias AnimatableSectionModel = RxDataSources.AnimatableSectionModel<IdentifiableSectionNode, IdentifiableNode>
let disposeBag = DisposeBag()
let delegateProxy = TableViewDelegateProxy()
public let sectionProviders: BehaviorRelay<[AnimatableTableViewSectionProvider]>
var nodeProviders: [String: _TableViewMultiNodeProvider] = [:] {
didSet {
nodeProviders.forEach { (_, provider) in
provider._register(tableView)
}
}
}
var footerSectionProviders: [String: _SectionPartionTableViewProvider] = [:] {
didSet {
footerSectionProviders.forEach { (_, provider) in
provider.register(tableView)
}
}
}
var headerSectionProviders: [String: _SectionPartionTableViewProvider] = [:] {
didSet {
headerSectionProviders.forEach { (_, provider) in
provider.register(tableView)
}
}
}
weak var _tableView: UITableView?
var tableView: UITableView {
return _tableView!
}
public var decideViewTransition: (([ChangesetInfo]) -> ViewTransition)?
public init(tableView: UITableView, sectionProviders: [AnimatableTableViewSectionProvider]) {
self._tableView = tableView
self.sectionProviders = BehaviorRelay(value: sectionProviders)
let dataSource = RxTableViewSectionedAnimatedDataSource<AnimatableSectionModel>(configureCell: { [weak self] dataSource, tableView, indexPath, node in
guard let provider = self?.nodeProviders[node.providerIdentity] else { return UITableViewCell() }
return provider._configureCell(tableView, indexPath: indexPath, node: node)
})
dataSource.decideViewTransition = { [weak self] (_, _, changesets) -> ViewTransition in
return self?.decideViewTransition?(changesets) ?? ViewTransition.animated
}
dataSource.animationConfiguration = AnimationConfiguration(
insertAnimation: .fade,
reloadAnimation: .none,
deleteAnimation: .fade
)
self.build(dataSource: dataSource)
self.sectionProviders.asObservable()
.do(onNext: { [weak self] (sectionProviders) in
self?.nodeProviders = Dictionary(
uniqueKeysWithValues: sectionProviders
.flatMap { $0.animatableProviders.flatMap { $0.__providers.map { (key: $0._flix_identity, value: $0) } }
})
self?.footerSectionProviders = Dictionary(
uniqueKeysWithValues: sectionProviders.lazy.compactMap { $0.animatableFooterProvider.map { (key: $0._flix_identity, value: $0) } })
self?.headerSectionProviders = Dictionary(
uniqueKeysWithValues: sectionProviders.lazy.compactMap { $0.animatableHeaderProvider.map { (key: $0._flix_identity, value: $0) } })
})
.flatMapLatest { (providers) -> Observable<[AnimatableSectionModel]> in
let sections: [Observable<(section: IdentifiableSectionNode, nodes: [IdentifiableNode])?>] = providers.map { $0.createSectionModel() }
return Observable.combineLatest(sections)
.ifEmpty(default: [])
.map { value -> [AnimatableSectionModel] in
return BuilderTool.combineSections(value)
}
}
.sendLatest(when: performGroupUpdatesBehaviorRelay)
.debounce(.seconds(0), scheduler: MainScheduler.instance)
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
public convenience init(tableView: UITableView, providers: [_AnimatableTableViewMultiNodeProvider]) {
let sectionProviderTableViewBuilder = AnimatableTableViewSectionProvider(
providers: providers,
headerProvider: nil,
footerProvider: nil
)
self.init(tableView: tableView, sectionProviders: [sectionProviderTableViewBuilder])
}
}
|
d5fcb0cd29402e296b9729708ff7a50e
| 39.490909 | 158 | 0.635833 | false | false | false | false |
wangela/wittier
|
refs/heads/master
|
wittier/Views/ProfileHeaderContentView.swift
|
mit
|
1
|
//
// ProfileHeaderContentView.swift
// wittier
//
// Created by Angela Yu on 10/7/17.
// Copyright © 2017 Angela Yu. All rights reserved.
//
import UIKit
class ProfileHeaderContentView: UIView {
// MARK: - Properties
@IBOutlet weak var profileBackgroundImageView: UIImageView!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screennameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var followingCountLabel: UILabel!
@IBOutlet weak var followerCountLabel: UILabel!
var user: User!
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
if user != nil {
getProfileLabels()
getProfileImages()
profileImageView.layer.cornerRadius = profileImageView.frame.size.width * 0.5
profileImageView.clipsToBounds = true
self.layoutIfNeeded()
}
}
// MARK: - Populate content
func getProfileImages() {
guard let profileURL = user.profileURL else {
profileImageView.image = nil
return
}
profileImageView.setImageWith(profileURL)
guard let profileBackgroundURL = user.profileBackgroundURL else {
profileBackgroundImageView.image = nil
let gradient = CAGradientLayer()
gradient.frame = profileBackgroundImageView.frame
gradient.colors = [UIColor.clear.cgColor, UIColor.white.cgColor]
profileBackgroundImageView.layer.insertSublayer(gradient, at: UInt32(profileBackgroundImageView.frame.minX))
return
}
profileBackgroundImageView.setImageWith(profileBackgroundURL)
}
func getProfileLabels() {
guard let userr = user else {
print("nil user in profile header")
return
}
nameLabel.text = userr.name
screennameLabel.text = userr.screenname
descriptionLabel.text = userr.tagline
locationLabel.text = userr.location
followerCountLabel.text = userr.followerCount
followingCountLabel.text = userr.followingCount
}
}
|
06f33e0bf9919370f0c21e3c463c66b0
| 30.539474 | 120 | 0.639967 | false | false | false | false |
asm-products/giraff-ios
|
refs/heads/master
|
Fun/DesignableTextField.swift
|
agpl-3.0
|
1
|
enum TextFieldValidation {
case Valid, Invalid, Unknown
}
@IBDesignable class DesignableTextField: UITextField {
@IBOutlet var nextTextField: UITextField?
@IBInspectable var leftPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, leftPadding, 0))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
}
}
@IBInspectable var rightPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, 0, rightPadding))
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var validColor: UIColor = UIColor(red:0.25, green:0.68, blue:0.35, alpha:1)
@IBInspectable var invalidColor: UIColor = UIColor(red:0.73, green:0.24, blue:0.17, alpha:1)
@IBInspectable var defaultColor: UIColor = UIColor(red:0.59, green:0.65, blue:0.71, alpha:1)
var validated: TextFieldValidation = .Unknown {
didSet {
switch (validated) {
case .Valid:
self.borderColor = validColor
case .Invalid:
self.borderColor = invalidColor
case .Unknown:
self.borderColor = defaultColor
}
}
}
}
|
fae9d0af1ddcddd38a0ec000e1ba9ca2
| 26.8125 | 96 | 0.568859 | false | false | false | false |
DNixonLLC/Path-of-Least-Resistance
|
refs/heads/master
|
Path-of-Least-Resistance/Path-of-Least-Resistance/PathOfLeastResistance.swift
|
mit
|
1
|
//
// PathOfLeastResistance.swift
// Path-of-Least-Resistance
//
// Created by Derek Nixon on 7/5/16.
// Copyright © 2016 Derek Nixon. All rights reserved.
//
import Foundation
class PathOfLeastResistance {
static let MaximumTotalResistance: Int = 50
struct Movement {
var row: Int
var column: Int
var value: Int
init(row: Int, column: Int, value: Int) {
self.row = row
self.column = column
self.value = value
}
}
enum PathOfLeastResistanceErrors: ErrorType {
case AttemptedMoveFromInvalidRow
case AttemptedMoveFromInvalidColumn
}
struct PathAnalysis : CustomStringConvertible {
var completePathFound: Bool = true
var totalResistance: Int = 0
var rowsTraversed: [Int] = [Int]()
var sourceMovement: Movement = Movement(row: 0, column: 0, value: 0)
var wasCompletePathFound: String {
get {
return (completePathFound == true) ? "Yes" : "No"
}
}
var description: String {
var formattedTraversedRows = ""
for row in rowsTraversed {
formattedTraversedRows += "\(row) "
}
formattedTraversedRows = formattedTraversedRows.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceCharacterSet())
return "\(wasCompletePathFound)\n\(totalResistance)\n\(formattedTraversedRows)\n"
}
}
var pathAnalysis: PathAnalysis = PathAnalysis()
func getNextMovements(grid: Grid, row: Int, column: Int) throws -> [Movement] {
let nextColumn = column + 1
let upperRow = (row == 0) ? grid.NumberOfRows - 1 : row - 1
let lowerRow = (row == (grid.NumberOfRows - 1)) ? 0 : row + 1
guard ((row >= 0) && (row < grid.NumberOfRows)) else {
throw PathOfLeastResistance.PathOfLeastResistanceErrors.AttemptedMoveFromInvalidRow
}
guard (column >= 0) else {
throw PathOfLeastResistanceErrors.AttemptedMoveFromInvalidColumn
}
guard (nextColumn <= (grid.NumberOfColumns - 1)) else {
return []
}
switch (grid.NumberOfRows) {
case 1:
return [Movement(row: row, column: nextColumn, value: grid[row, nextColumn])]
case 2:
return [
Movement(row: upperRow, column: nextColumn, value: grid[upperRow, nextColumn]),
Movement(row: row, column: nextColumn, value: grid[row, nextColumn])
]
default:
return [
Movement(row: upperRow, column: nextColumn, value: grid[upperRow, nextColumn]),
Movement(row: row, column: nextColumn, value: grid[row, nextColumn]),
Movement(row: lowerRow, column: nextColumn, value: grid[lowerRow, nextColumn])
]
}
}
func determinePathOfLeastResistance(grid: Grid) -> PathAnalysis {
let numberOfColumns = grid.NumberOfColumns
var possiblePaths: [PathAnalysis] = [PathAnalysis]()
possiblePaths = createInitialPaths(grid)
for column in 1 ..< numberOfColumns {
possiblePaths = analyzePossiblePathsWithinColumn(grid, column: column, existingPaths: possiblePaths)
}
return determineBestPath(possiblePaths)
}
private func determineBestPath(paths: [PathAnalysis]) -> PathAnalysis {
var anyCompletePaths: Bool = false
var bestCompletePath: PathAnalysis = PathAnalysis()
var bestIncompletePath: PathAnalysis = PathAnalysis()
var bestIncompleteDiff: Int = PathOfLeastResistance.MaximumTotalResistance
var currentIncompleteDiff: Int = 0
bestCompletePath.totalResistance = Int.max
for path in paths {
if (path.completePathFound) {
anyCompletePaths = true
if (path.totalResistance < bestCompletePath.totalResistance) {
bestCompletePath = path
}
} else {
// Our "best" incomplete path is the one that came the closest to our threshold
currentIncompleteDiff = PathOfLeastResistance.MaximumTotalResistance - path.totalResistance
if ((currentIncompleteDiff < bestIncompleteDiff) && (currentIncompleteDiff > 0)) {
bestIncompletePath = path
bestIncompleteDiff = PathOfLeastResistance.MaximumTotalResistance - bestIncompletePath.totalResistance
}
}
}
return (anyCompletePaths) ? bestCompletePath : bestIncompletePath
}
private func createInitialPaths(grid: Grid) -> [PathAnalysis] {
let column: Int = 0
let numberOfRows: Int = grid.NumberOfRows
var analyses: [PathAnalysis] = [PathAnalysis]()
var moves: [Movement] = [Movement]()
var currentPath: PathAnalysis
var existingPath: PathAnalysis
for row in 0 ..< numberOfRows {
moves = try! getNextMovements(grid, row: row, column: column)
for move in moves {
existingPath = PathAnalysis()
existingPath.completePathFound = true
existingPath.totalResistance = grid[row, column]
existingPath.rowsTraversed.append(row + 1) // 1-based indexing on rows traversed
currentPath = updatePathAnalysisForGridCell(
grid,
row: move.row,
column: move.column,
existingPath: existingPath)
currentPath.sourceMovement = move
analyses.append(currentPath)
}
}
return analyses
}
private func analyzePossiblePathsWithinColumn(grid: Grid, column: Int, existingPaths: [PathAnalysis]) -> [PathAnalysis] {
var analyses: [PathAnalysis] = [PathAnalysis]()
var moves: [Movement] = [Movement]()
var rowIndex: Int = 0
var currentPath: PathAnalysis
for path in existingPaths {
rowIndex = path.sourceMovement.row
moves = try! getNextMovements(grid, row: rowIndex, column: column)
if (moves.count == 0) {
// No more moves... our existing path is best known
analyses.append(path)
} else {
for move in moves {
currentPath = updatePathAnalysisForGridCell(
grid, row: move.row, column: move.column, existingPath: path)
currentPath.sourceMovement = move
analyses.append(currentPath)
}
}
}
return analyses
}
private func updatePathAnalysisForGridCell(grid: Grid, row: Int, column: Int, existingPath: PathAnalysis) -> PathAnalysis {
var newPath: PathAnalysis = existingPath
var totalResistance: Int = 0
if (existingPath.completePathFound) {
totalResistance = existingPath.totalResistance + grid[row, column]
newPath.completePathFound = (totalResistance <= PathOfLeastResistance.MaximumTotalResistance)
if (newPath.completePathFound) {
newPath.totalResistance = totalResistance
newPath.rowsTraversed.append(row + 1) // 1-based indexing on reported/analyzed rows
}
}
return newPath
}
}
extension PathOfLeastResistance.Movement: Equatable {}
func ==(lhs: PathOfLeastResistance.Movement, rhs: PathOfLeastResistance.Movement) -> Bool {
return
lhs.row == rhs.row &&
lhs.column == rhs.column &&
lhs.value == rhs.value
}
|
dc27ab8c4972c63c0aae442d46e46a76
| 35.68018 | 127 | 0.570429 | false | false | false | false |
CoderJackyHuang/ITClient-Swift
|
refs/heads/master
|
ITClient-Swift/Category/UIViewController+HYBExtension.swift
|
mit
|
1
|
//
// UIViewController+HYBExtension.swift
// ITClient-Swift
//
// Created by huangyibiao on 15/9/25.
// Copyright © 2015年 huangyibiao. All rights reserved.
//
import Foundation
import UIKit
public enum AlertOKCancelDirection: Int {
case OkCancel
case CancelOk
}
private var sg_hyb_alert_actionsheet_controller: UIAlertController?
private var sg_default_ok_button_title = "确定"
private var sg_default_cancel_button_title = "取消"
private var sg_ok_cancel_button_direction = AlertOKCancelDirection.CancelOk
/// UIViewController extension for AlertView and ActionSheet
///
/// Author: 黄仪标
/// Blog: http://www.hybblog.com/
/// Github: http://github.com/CoderJackyHuang/
/// Email: [email protected]
/// Weibo: JackyHuang(标哥)
public extension UIViewController {
/// Get/Set the default ok button title
public var hyb_defaultOkTitle: String {
get { return sg_default_ok_button_title }
set { sg_default_ok_button_title = newValue }
}
/// Get/Set the default cance button title
public var hyb_defaultCancelTitle: String {
get { return sg_default_cancel_button_title }
set { sg_default_cancel_button_title = newValue }
}
/// Get/Set the defaul direction between ok button and cancel button. Default is CacelOk.
public var hyb_okCancelDirection: AlertOKCancelDirection {
get { return sg_ok_cancel_button_direction }
set { sg_ok_cancel_button_direction = newValue }
}
// MARK: Ok Alert
/// Only Show Alert View in current controller
///
/// - parameter title: title
public func hyb_showOkAlert(title: String?) {
self.hyb_showOkAlert(title, message: nil)
}
/// Show Alert view in current controller with a ok button
///
/// - parameter title: alert view's title
/// - parameter message: show the message
public func hyb_showOkAlert(title: String?, message: String?) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultOkTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
})])
}
/// Show title and an ok button of Alert
///
/// - parameter title: alert's title
/// - parameter ok: ok button call back
public func hyb_showOkAlert(title: String?, ok: () ->Void) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultOkTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
ok()
})])
}
/// Show title, message and an ok button of Alert
///
/// - parameter title: title
/// - parameter message: message
/// - parameter ok: ok button call back
public func hyb_showOkAlert(title: String?, message: String?, ok: () ->Void) {
self.hyb_showAlertActionSheet(title, message: message, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultOkTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
ok()
})])
}
// MARK: Cancel Alert
/// Only Show Alert View in current controller
///
/// - parameter title: title
public func hyb_showCancelAlert(title: String?) {
self.hyb_showCancelAlert(title, message: nil)
}
/// Show Alert view in current controller with a cancel button
///
/// - parameter title: alert view's title
/// - parameter message: show the message
public func hyb_showCancelAlert(title: String?, message: String?) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultCancelTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
})])
}
/// Show title and an ok button of Alert
///
/// - parameter title: alert's title
/// - parameter cancel: cancel button call back
public func hyb_showCancelAlert(title: String?, cancel: () ->Void) {
self.hyb_showAlertActionSheet(title, message: nil, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultCancelTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
cancel()
})])
}
/// Show title, message and an ok button of Alert
///
/// - parameter title: title
/// - parameter message: message
/// - parameter cancel: cancel button call back
public func hyb_showCancelAlert(title: String?, message: String?, cancel: () ->Void) {
self.hyb_showAlertActionSheet(title, message: message, preferredStyle: .Alert, alertActions: [UIAlertAction(title: self.hyb_defaultCancelTitle, style: .Default, handler: { (e) -> Void in
sg_hyb_alert_actionsheet_controller = nil
cancel()
})])
}
// MARK: Ok And Cancel Alert
/// Show Ok and cancel alert view
///
/// - parameter title: title
public func hyb_showAlert(title: String?) {
self.hyb_showAlert(title, message: nil)
}
/// Show Ok and cancel alert view with title and message
///
/// - parameter title: title
/// - parameter message: message
public func hyb_showAlert(title: String?, message: String?) {
var buttonTitles: [String]!
if self.hyb_okCancelDirection == .OkCancel {
buttonTitles = [self.hyb_defaultOkTitle, self.hyb_defaultCancelTitle]
} else {
buttonTitles = [self.hyb_defaultCancelTitle, self.hyb_defaultOkTitle]
}
self.hyb_showAlert(title, message: message, buttonTitles: buttonTitles) { (index) -> Void in
sg_hyb_alert_actionsheet_controller = nil
}
}
/// Show alert view with title, message and custom button titles.
///
/// - parameter title: title
/// - parameter message: message
/// - parameter buttonTitles: custom button titles
/// - parameter buttonClosure: call back
public func hyb_showAlert(title: String?, message: String?, buttonTitles: [String]?, buttonClosure: ((index: Int) ->Void)?) {
var buttonArray: [UIAlertAction]?
if let titles = buttonTitles {
for (index, item) in titles.enumerate() {
buttonArray?.append(UIAlertAction(title: item, style: .Default, handler: { (e) -> Void in
if let callback = buttonClosure {
sg_hyb_alert_actionsheet_controller = nil
callback(index: index)
}
}))
}
}
self.hyb_showAlertActionSheet(title, message: message, preferredStyle: .Alert, alertActions: buttonArray)
}
// MARK: Private
private func hyb_showAlertActionSheet(title: String?, message: String?, preferredStyle: UIAlertControllerStyle, alertActions: [UIAlertAction]?) {
// prevent show too many times
guard let _ = sg_hyb_alert_actionsheet_controller else {
return
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
if let actions = alertActions {
for alertAction in actions {
alertController.addAction(alertAction)
}
}
sg_hyb_alert_actionsheet_controller = alertController
self.presentViewController(alertController, animated: true, completion: nil)
}
}
|
c04f8f61d3b05bea7159c34c0f712c76
| 35.256281 | 190 | 0.675492 | false | false | false | false |
KrishMunot/swift
|
refs/heads/master
|
test/SILGen/erasure_reabstraction.swift
|
apache-2.0
|
8
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
struct Foo {}
class Bar {}
// CHECK: [[CONCRETE:%.*]] = init_existential_addr [[EXISTENTIAL:%.*]] : $*protocol<>, $Foo.Type
// CHECK: [[METATYPE:%.*]] = metatype $@thick Foo.Type
// CHECK: store [[METATYPE]] to [[CONCRETE]] : $*@thick Foo.Type
let x: Any = Foo.self
// CHECK: [[CONCRETE:%.*]] = init_existential_addr [[EXISTENTIAL:%.*]] : $*protocol<>, $() -> ()
// CHECK: [[CLOSURE:%.*]] = function_ref
// CHECK: [[CLOSURE_THICK:%.*]] = thin_to_thick_function [[CLOSURE]]
// CHECK: [[REABSTRACTION_THUNK:%.*]] = function_ref @_TTRXFo___XFo_iT__iT__
// CHECK: [[CLOSURE_REABSTRACTED:%.*]] = partial_apply [[REABSTRACTION_THUNK]]([[CLOSURE_THICK]])
// CHECK: store [[CLOSURE_REABSTRACTED]] to [[CONCRETE]]
let y: Any = {() -> () in ()}
|
f717201d0a93f3bb55a786ddd4cbad95
| 41.210526 | 97 | 0.602244 | false | false | false | false |
prebid/prebid-mobile-ios
|
refs/heads/master
|
EventHandlers/PrebidMobileGAMEventHandlersTests/TestModels/PropertyTestModels.swift
|
apache-2.0
|
1
|
/* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import XCTest
class BasePropTest<T> {
let file: StaticString
let line: UInt
init(file: StaticString = #file, line: UInt = #line) {
self.file = file
self.line = line
}
func run(object: T) {}
}
class PropTest<T, V: Equatable>: BasePropTest<T> {
let keyPath: ReferenceWritableKeyPath<T, V>
let value: V
init(keyPath: ReferenceWritableKeyPath<T, V>, value: V, file: StaticString = #file, line: UInt = #line) {
self.keyPath = keyPath
self.value = value
super.init(file: file, line: line)
}
override func run(object: T) {
object[keyPath: keyPath] = value
let readValue = object[keyPath: keyPath]
XCTAssertEqual(readValue, value, file: file, line: line)
}
}
class RefPropTest<T, V: NSObjectProtocol>: BasePropTest<T> {
let keyPath: ReferenceWritableKeyPath<T, V?>
let value: V
init(keyPath: ReferenceWritableKeyPath<T, V?>, value: V, file: StaticString = #file, line: UInt = #line) {
self.keyPath = keyPath
self.value = value
super.init(file: file, line: line)
}
override func run(object: T) {
object[keyPath: keyPath] = value
let readValue = object[keyPath: keyPath]
XCTAssertEqual(readValue as? NSObject?, value as? NSObject, file: file, line: line)
}
}
class RefProxyPropTest<T, V: NSObjectProtocol>: BasePropTest<T> {
let keyPath: ReferenceWritableKeyPath<T, V?>
let value: V
init(keyPath: ReferenceWritableKeyPath<T, V?>, value: V, file: StaticString = #file, line: UInt = #line) {
self.keyPath = keyPath
self.value = value
super.init(file: file, line: line)
}
override func run(object: T) {
object[keyPath: keyPath] = value
let _ = object[keyPath: keyPath]
// Do nothing since there is no storage for value yet. We just test properties.
//XCTAssertEqual(readValue as? NSObject?, value as? NSObject, file: file, line: line)
}
}
class DicPropTest<T, K: Hashable, V>: BasePropTest<T> {
let keyPath: ReferenceWritableKeyPath<T, [K: V]?>
let value: [K: V]
init(keyPath: ReferenceWritableKeyPath<T, [K: V]?>, value: [K: V], file: StaticString = #file, line: UInt = #line) {
self.keyPath = keyPath
self.value = value
super.init(file: file, line: line)
}
override func run(object: T) {
object[keyPath: keyPath] = value
let readValue = object[keyPath: keyPath]
XCTAssertEqual(readValue as NSDictionary?, value as NSDictionary, file: file, line: line)
}
}
|
5395e30d56034e289d99627de28fc31b
| 31.727273 | 120 | 0.646605 | false | true | false | false |
samnm/material-components-ios
|
refs/heads/develop
|
components/AnimationTiming/examples/AnimationTimingExample.swift
|
apache-2.0
|
1
|
/*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents.MaterialAnimationTiming
struct Constants {
struct AnimationTime {
static let interval: Double = 1.0
static let delay: Double = 0.5
}
struct Sizes {
static let topMargin: CGFloat = 16.0
static let leftGutter: CGFloat = 16.0
static let textOffset: CGFloat = 16.0
static let circleSize: CGSize = CGSize(width: 48.0, height: 48.0)
}
}
class AnimationTimingExample: UIViewController {
fileprivate let scrollView: UIScrollView = UIScrollView()
fileprivate let linearView: UIView = UIView()
fileprivate let materialStandardView: UIView = UIView()
fileprivate let materialDecelerationView: UIView = UIView()
fileprivate let materialAccelerationView: UIView = UIView()
fileprivate let materialSharpView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
title = "Animation Timing"
setupExampleViews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let timeInterval: TimeInterval = 2 * (Constants.AnimationTime.interval + Constants.AnimationTime.delay)
var _: Timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(self.playAnimations), userInfo: nil, repeats: true)
playAnimations()
}
func playAnimations() {
let linearCurve: CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
applyAnimation(toView: linearView, withTimingFunction: linearCurve)
if let materialStandard = CAMediaTimingFunction.mdc_function(withType: .standard) {
applyAnimation(toView: materialStandardView, withTimingFunction: materialStandard)
} else {
materialStandardView.removeFromSuperview()
}
if let materialDeceleration = CAMediaTimingFunction.mdc_function(withType: .deceleration) {
applyAnimation(toView: materialDecelerationView, withTimingFunction: materialDeceleration)
} else {
materialDecelerationView.removeFromSuperview()
}
if let materialAcceleration = CAMediaTimingFunction.mdc_function(withType: .acceleration) {
applyAnimation(toView: materialAccelerationView, withTimingFunction: materialAcceleration)
} else {
materialAccelerationView.removeFromSuperview()
}
if let materialSharp = CAMediaTimingFunction.mdc_function(withType: .sharp) {
applyAnimation(toView: materialSharpView, withTimingFunction: materialSharp)
} else {
materialSharpView.removeFromSuperview()
}
}
func applyAnimation(toView view: UIView, withTimingFunction timingFunction : CAMediaTimingFunction) {
let animWidth: CGFloat = self.view.frame.size.width - view.frame.size.width - 32.0
let transform: CGAffineTransform = CGAffineTransform.init(translationX: animWidth, y: 0)
UIView.mdc_animate(with: timingFunction, duration: Constants.AnimationTime.interval, delay: Constants.AnimationTime.delay, options: [], animations: {
view.transform = transform
}, completion: { Bool in
UIView.mdc_animate(with: timingFunction, duration: Constants.AnimationTime.interval, delay: Constants.AnimationTime.delay, options: [], animations: {
view.transform = CGAffineTransform.identity
}, completion: nil)
})
}
}
extension AnimationTimingExample {
fileprivate func setupExampleViews() {
let curveLabel: (String) -> UILabel = { labelTitle in
let label: UILabel = UILabel()
label.text = labelTitle
label.font = MDCTypography.captionFont()
label.textColor = UIColor(white: 0, alpha: MDCTypography.captionFontOpacity())
label.sizeToFit()
return label
}
let defaultColors: [UIColor] = [UIColor.darkGray.withAlphaComponent(0.8),
UIColor.darkGray.withAlphaComponent(0.65),
UIColor.darkGray.withAlphaComponent(0.5),
UIColor.darkGray.withAlphaComponent(0.35),
UIColor.darkGray.withAlphaComponent(0.2)]
scrollView.frame = view.bounds
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.contentSize = CGSize(width: view.frame.width,
height: view.frame.height + Constants.Sizes.topMargin)
scrollView.clipsToBounds = true
view.addSubview(scrollView)
let lineSpace: CGFloat = (view.frame.size.height - 50.0) / 5.0
let linearLabel: UILabel = curveLabel("Linear")
linearLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: Constants.Sizes.topMargin, width: linearLabel.frame.size.width, height: linearLabel.frame.size.height)
scrollView.addSubview(linearLabel)
let linearViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: Constants.Sizes.leftGutter + Constants.Sizes.topMargin, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height)
linearView.frame = linearViewFrame
linearView.backgroundColor = defaultColors[0]
linearView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0
scrollView.addSubview(linearView)
let materialEaseInOutLabel: UILabel = curveLabel("MDCAnimationTimingFunctionEaseInOut")
materialEaseInOutLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace, width: materialEaseInOutLabel.frame.size.width, height: materialEaseInOutLabel.frame.size.height)
scrollView.addSubview(materialEaseInOutLabel)
let materialEaseInOutViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height)
materialStandardView.frame = materialEaseInOutViewFrame
materialStandardView.backgroundColor = defaultColors[1]
materialStandardView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0
scrollView.addSubview(materialStandardView)
let materialEaseOutLabel: UILabel = curveLabel("MDCAnimationTimingFunctionEaseOut")
materialEaseOutLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 2.0, width: materialEaseOutLabel.frame.size.width, height: materialEaseOutLabel.frame.size.height)
scrollView.addSubview(materialEaseOutLabel)
let materialEaseOutViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 2.0 + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height)
materialDecelerationView.frame = materialEaseOutViewFrame
materialDecelerationView.backgroundColor = defaultColors[2]
materialDecelerationView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0
scrollView.addSubview(materialDecelerationView)
let materialEaseInLabel: UILabel = curveLabel("MDCAnimationTimingFunctionEaseIn")
materialEaseInLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 3.0, width: materialEaseInLabel.frame.size.width, height: materialEaseInLabel.frame.size.height)
scrollView.addSubview(materialEaseInLabel)
let materialEaseInViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 3.0 + Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height)
materialAccelerationView.frame = materialEaseInViewFrame
materialAccelerationView.backgroundColor = defaultColors[3]
materialAccelerationView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0
scrollView.addSubview(materialAccelerationView)
let materialSharpLabel: UILabel = curveLabel("MDCAnimationTimingSharp")
materialSharpLabel.frame = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 4.0, width: materialSharpLabel.frame.size.width, height: materialSharpLabel.frame.size.height)
scrollView.addSubview(materialSharpLabel)
let materialSharpViewFrame: CGRect = CGRect(x: Constants.Sizes.leftGutter, y: lineSpace * 4.0 +
Constants.Sizes.textOffset, width: Constants.Sizes.circleSize.width, height: Constants.Sizes.circleSize.height)
materialSharpView.frame = materialSharpViewFrame
materialSharpView.backgroundColor = defaultColors[4]
materialSharpView.layer.cornerRadius = Constants.Sizes.circleSize.width / 2.0
scrollView.addSubview(materialSharpView)
}
@objc class func catalogBreadcrumbs() -> [String] {
return ["Animation Timing", "Animation Timing (Swift)"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
@objc class func catalogIsPresentable() -> Bool {
return true
}
}
|
f6b7cc1f48dc453e079dba4776bdb7f6
| 48.145078 | 216 | 0.732314 | false | false | false | false |
HongliYu/DPSlideMenuKit-Swift
|
refs/heads/master
|
DPSlideMenuKitDemo/DPSlideMenuKit/DPDrawerViewController.swift
|
mit
|
1
|
//
// DPDrawerViewController.swift
// DPSlideMenuKitDemo
//
// Created by Hongli Yu on 8/17/16.
// Copyright © 2016 Hongli Yu. All rights reserved.
//
import UIKit
public class DPDrawerViewController: UIViewController, UIGestureRecognizerDelegate {
// Controller
private var leftMenuViewController: DPLeftMenuViewController?
private var rightMenuViewController: DPRightMenuViewController?
private var centerContentViewController: DPCenterContentViewController?
// State
private(set) var drawerState: DrawerControllerState = .closed
// View
private lazy var leftView: UIView = {
UIView(frame: view.bounds)
}()
private lazy var rightView: DPDropShadowView = {
DPDropShadowView(frame: view.bounds)
}()
private lazy var centerView: DPDropShadowView = {
DPDropShadowView(frame: self.view.bounds)
}()
// Gesture, make sure self is initialized before being binded to a gesture
private lazy var tapGestureRecognizer: UITapGestureRecognizer = {
UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized(_:)))
}()
private lazy var panGestureRecognizer: UIPanGestureRecognizer = {
UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognized(_:)))
}()
private var panGestureStartLocation = CGPoint.zero
// Status bar
private var statusBarHidden = false {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
open override var prefersStatusBarHidden: Bool {
return statusBarHidden
}
func config(_ centerContentViewController: DPCenterContentViewController,
leftViewController: DPLeftMenuViewController?,
rightMenuViewController: DPRightMenuViewController?) {
self.centerContentViewController = centerContentViewController
self.leftMenuViewController = leftViewController
self.rightMenuViewController = rightMenuViewController
self.basicUI()
}
func basicUI() {
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
leftView.autoresizingMask = view.autoresizingMask
rightView.autoresizingMask = view.autoresizingMask
centerView.autoresizingMask = view.autoresizingMask
// Add the center view container
view.addSubview(centerView)
// Add the center view controller to the container
addCenterViewController()
setupGestureRecognizers()
}
func addCenterViewController() {
guard let centerContentViewController = centerContentViewController else { return }
addChild(centerContentViewController)
centerContentViewController.view.frame = view.bounds
centerView.addSubview(centerContentViewController.view)
centerContentViewController.didMove(toParent: self)
}
// MARK: Gestures
func setupGestureRecognizers() {
panGestureRecognizer.maximumNumberOfTouches = 1
panGestureRecognizer.delegate = self
centerView.addGestureRecognizer(panGestureRecognizer)
}
func addClosingGestureRecognizers() {
centerView.addGestureRecognizer(tapGestureRecognizer)
}
func removeClosingGestureRecognizers() {
centerView.removeGestureRecognizer(tapGestureRecognizer)
}
@objc func tapGestureRecognized(_ tapGestureRecognizer: UITapGestureRecognizer) {
if (tapGestureRecognizer.state == .ended) {
switch drawerState {
case .leftOpen:
leftClose()
case .rightOpen:
rightClose()
default: break
}
}
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let velocity = (gestureRecognizer as? UIPanGestureRecognizer)?.velocity(in: view) else {
return false
}
let velocityX = velocity.x
switch drawerState {
case .closed :
return true
case .leftOpen:
return velocityX < CGFloat(0.0) // rightWillOpen
case .rightOpen:
return velocityX > CGFloat(0.0) // leftWillOpen
default:
return false
}
}
@objc func panGestureRecognized(_ panGestureRecognizer: UIPanGestureRecognizer) {
let state = panGestureRecognizer.state
let location = panGestureRecognizer.location(in: view)
let velocity = panGestureRecognizer.velocity(in: view)
let velocitX = velocity.x
switch state {
case .began:
panGestureStartLocation = location
if drawerState == .closed {
if velocitX < -kDPGestureSensitivityValue {
rightWillOpen()
}
if velocitX > kDPGestureSensitivityValue {
leftWillOpen()
}
} else {
if drawerState == .leftOpen {
leftWillClose()
}
if drawerState == .rightOpen {
rightWillClose()
}
}
case .changed:
if drawerState == .leftOpening || drawerState == .leftClosing {
var delta: CGFloat = 0.0
if drawerState == .leftOpening {
delta = location.x - panGestureStartLocation.x
} else if drawerState == .leftClosing {
delta = (UIScreen.main.bounds.width
- kDPDrawerControllerDrawerWidthGapOffset)
- (panGestureStartLocation.x - location.x)
}
var leftFrame = leftView.frame
var centerFrame = centerView.frame
if delta > (UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset) {
leftFrame.origin.x = 0.0
centerFrame.origin.x = UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset
} else if delta < 0.0 {
leftFrame.origin.x = kDPDrawerControllerLeftViewInitialOffset
centerFrame.origin.x = 0.0
} else {
// parallax effect
leftFrame.origin.x = kDPDrawerControllerLeftViewInitialOffset
- (delta * kDPDrawerControllerLeftViewInitialOffset)
/ (UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset)
centerFrame.origin.x = delta
}
leftView.frame = leftFrame
centerView.frame = centerFrame
}
if drawerState == .rightOpening || drawerState == .rightClosing {
if drawerState == .rightOpening {
let delta: CGFloat = panGestureStartLocation.x - location.x
let positiveDelta = (delta >= 0) ? delta : 0
var rightFrame = rightView.frame
rightFrame.origin.x = view.bounds.width + kDPDrawerControllerDrawerWidthGapOffset - positiveDelta
rightView.frame = rightFrame
} else if drawerState == .rightClosing {
let delta: CGFloat = location.x - panGestureStartLocation.x
let positiveDelta = (delta >= 0) ? delta : 0
var rightFrame = rightView.frame
rightFrame.origin.x = kDPDrawerControllerDrawerWidthGapOffset + positiveDelta
rightView.frame = rightFrame
}
}
case .ended:
if drawerState == .leftOpening {
let centerViewLocationX: CGFloat = centerView.frame.origin.x
if centerViewLocationX == (UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset) {
leftDidOpen()
} else if (centerViewLocationX > view.bounds.size.width / 3.0 && velocity.x > 0.0) {
self.leftOpening(animated: true)
} else {
leftDidOpen()
leftWillClose()
leftClosing(animated: true)
}
} else if drawerState == .leftClosing {
let centerViewLocationX: CGFloat = centerView.frame.origin.x
if centerViewLocationX == 0.0 {
// Close the drawer without animation, as it has already being dragged in its final position
leftDidClose()
} else if centerViewLocationX < (2 * view.bounds.size.width) / 3.0, velocity.x < 0.0 {
leftClosing(animated: true)
} else {
leftDidClose()
let leftFrame: CGRect = leftView.frame
leftWillOpen()
leftView.frame = leftFrame
leftOpening(animated: true)
}
}
if drawerState == .rightOpening {
let rightViewLocationX: CGFloat = rightView.frame.origin.x
if rightViewLocationX == kDPDrawerControllerDrawerWidthGapOffset {
rightDidOpen()
} else if (rightViewLocationX < (2 * view.bounds.size.width) / 3.0
&& velocity.x < 0.0) {
rightOpening(animated: true)
} else {
rightDidOpen()
rightWillClose()
rightClosing(animated: true)
}
} else if drawerState == .rightClosing {
let rightViewLocationX: CGFloat = rightView.frame.origin.x
if rightViewLocationX == view.bounds.width {
// Close the drawer without animation, as it has already being dragged in its final position
rightDidClose()
} else if (rightViewLocationX > view.bounds.size.width / 3.0
&& velocity.x > 0.0) {
rightClosing(animated: true)
} else {
rightDidClose()
let rightFrame: CGRect = rightView.frame
rightWillOpen()
rightView.frame = rightFrame
rightOpening(animated: true)
}
}
default:
break
}
}
// MARK: Animations
private func leftOpening(animated: Bool) {
let leftViewFinalFrame: CGRect = view.bounds
var centerViewFinalFrame: CGRect = view.bounds
centerViewFinalFrame.origin.x = UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset
if animated {
UIView.animate(withDuration: kDPDrawerControllerAnimationDuration,
delay: 0,
usingSpringWithDamping: kDPDrawerControllerOpeningAnimationSpringDamping,
initialSpringVelocity: kDPDrawerControllerOpeningAnimationSpringInitialVelocity,
options: .curveLinear,
animations: {
self.centerView.frame = centerViewFinalFrame
self.leftView.frame = leftViewFinalFrame
}) { _ in
self.leftDidOpen()
}
} else {
centerView.frame = centerViewFinalFrame
leftView.frame = leftViewFinalFrame
leftDidOpen()
}
}
private func rightOpening(animated: Bool) {
var rightViewFinalFrame: CGRect = view.bounds
rightViewFinalFrame.origin.x = kDPDrawerControllerDrawerWidthGapOffset
if animated {
UIView.animate(withDuration: kDPDrawerControllerAnimationDuration,
delay: 0,
usingSpringWithDamping: kDPDrawerControllerOpeningAnimationSpringDamping,
initialSpringVelocity: kDPDrawerControllerOpeningAnimationSpringInitialVelocity,
options: .curveLinear,
animations: {
self.rightView.frame = rightViewFinalFrame
}) { _ in
self.rightDidOpen()
}
} else {
rightView.frame = rightViewFinalFrame
rightDidOpen()
}
}
private func leftClosing(animated: Bool) {
var leftViewFinalFrame: CGRect = leftView.frame
leftViewFinalFrame.origin.x = kDPDrawerControllerLeftViewInitialOffset
let centerViewFinalFrame: CGRect = view.bounds
if animated {
UIView.animate(withDuration: kDPDrawerControllerAnimationDuration,
delay: 0,
usingSpringWithDamping: kDPDrawerControllerClosingAnimationSpringDamping,
initialSpringVelocity: kDPDrawerControllerClosingAnimationSpringInitialVelocity,
options: .curveLinear,
animations: {
self.centerView.frame = centerViewFinalFrame
self.leftView.frame = leftViewFinalFrame
}) { _ in
self.leftDidClose()
}
} else {
centerView.frame = centerViewFinalFrame
leftView.frame = leftViewFinalFrame
leftDidClose()
}
}
private func rightClosing(animated: Bool) {
var rightViewFinalFrame: CGRect = rightView.frame
rightViewFinalFrame.origin.x = view.bounds.width + kDPDrawerControllerDrawerWidthGapOffset
if animated {
UIView.animate(withDuration: kDPDrawerControllerAnimationDuration,
delay: 0,
usingSpringWithDamping: kDPDrawerControllerClosingAnimationSpringDamping,
initialSpringVelocity: kDPDrawerControllerClosingAnimationSpringInitialVelocity,
options: .curveLinear,
animations: {
self.rightView.frame = rightViewFinalFrame
}) { _ in
self.rightDidClose()
}
} else {
rightView.frame = rightViewFinalFrame
rightDidClose()
}
}
// MARK: Opening the drawer
func leftOpen() {
leftWillOpen()
leftOpening(animated: true)
}
func rightOpen() {
rightWillOpen()
rightOpening(animated: true)
}
private func leftWillOpen() {
guard let leftMenuViewController = self.leftMenuViewController else { return }
statusBarHidden = true
drawerState = .leftOpening
// Position the left view
var frame: CGRect = view.bounds
frame.origin.x = kDPDrawerControllerLeftViewInitialOffset
leftView.frame = frame
// Start adding the left view controller to the container
addChild(leftMenuViewController)
leftMenuViewController.view.frame = leftView.bounds
leftView.addSubview(leftMenuViewController.view)
// Add the left view to the view hierarchy
view.insertSubview(leftView,
belowSubview: centerView)
// Notify the child view controllers that the drawer is about to open
leftMenuViewController.drawerControllerWillOpen?()
centerContentViewController?.drawerControllerWillOpen?(true)
}
private func rightWillOpen() {
guard let rightMenuViewController = self.rightMenuViewController else { return }
statusBarHidden = true
drawerState = .rightOpening
// Position the right view
var frame = view.bounds
frame.origin.x = view.bounds.width + kDPDrawerControllerDrawerWidthGapOffset
rightView.frame = frame
// Start adding the right view controller to the container
addChild(rightMenuViewController)
rightMenuViewController.view.frame = rightView.bounds
rightView.addSubview(rightMenuViewController.view)
// Add the right view to the view hierarchy
view.insertSubview(rightView, aboveSubview: centerView)
// Notify the child view controllers that the drawer is about to open
rightMenuViewController.drawerControllerWillOpen?()
centerContentViewController?.drawerControllerWillOpen?(false)
}
private func leftDidOpen() {
// Complete adding the left controller to the container
leftMenuViewController?.didMove(toParent: self)
addClosingGestureRecognizers()
// Keep track that the drawer is open
drawerState = .leftOpen
// Notify the child view controllers that the drawer is open
leftMenuViewController?.drawerControllerDidOpen?()
centerContentViewController?.drawerControllerDidOpen?(true)
}
private func rightDidOpen() {
// Complete adding the left controller to the container
rightMenuViewController?.didMove(toParent: self)
addClosingGestureRecognizers()
// Keep track that the drawer is open
drawerState = .rightOpen
// Notify the child view controllers that the drawer is open
rightMenuViewController?.drawerControllerDidOpen?()
centerContentViewController?.drawerControllerDidOpen?(false)
}
func leftClose() {
leftWillClose()
leftClosing(animated: true)
}
func rightClose() {
rightWillClose()
rightClosing(animated: true)
}
private func leftWillClose() {
// Start removing the left controller from the container
leftMenuViewController?.willMove(toParent: nil)
// Keep track that the drawer is closing
drawerState = .leftClosing
// Notify the child view controllers that the drawer is about to close
leftMenuViewController?.drawerControllerWillClose?()
centerContentViewController?.drawerControllerWillClose?(true)
}
private func rightWillClose() {
// Start removing the left controller from the container
rightMenuViewController?.willMove(toParent: nil)
// Keep track that the drawer is closing
drawerState = .rightClosing
// Notify the child view controllers that the drawer is about to close
rightMenuViewController?.drawerControllerWillClose?()
centerContentViewController?.drawerControllerWillClose?(false)
}
private func leftDidClose() {
statusBarHidden = false
// Complete removing the left view controller from the container
leftMenuViewController?.view.removeFromSuperview()
leftMenuViewController?.removeFromParent()
// Remove the left view from the view hierarchy
leftView.removeFromSuperview()
removeClosingGestureRecognizers()
// Keep track that the drawer is closed
drawerState = .closed
// Notify the child view controllers that the drawer is closed
leftMenuViewController?.drawerControllerDidClose?()
centerContentViewController?.drawerControllerDidClose?(true)
}
private func rightDidClose() {
statusBarHidden = false
// Complete removing the left view controller from the container
rightMenuViewController?.view.removeFromSuperview()
rightMenuViewController?.removeFromParent()
// Remove the left view from the view hierarchy
rightView.removeFromSuperview()
removeClosingGestureRecognizers()
// Keep track that the drawer is closed
drawerState = .closed
// Notify the child view controllers that the drawer is closed
rightMenuViewController?.drawerControllerDidClose?()
centerContentViewController?.drawerControllerDidClose?(false)
}
// MARK: Reloading / Replacing the center view controller
func leftMenuReloadCenterViewController(_ done: (()->Void)?) {
leftWillClose()
var frame = centerView.frame
frame.origin.x = view.bounds.size.width
UIView.animate(withDuration: kDPDrawerControllerAnimationDuration / 2.0, animations: {
self.centerView.frame = frame
}, completion: { _ in
done?()
self.leftClosing(animated: true)
})
}
func rightMenuReloadCenterViewController(_ done: (()->Void)?) {
rightWillClose()
var frame = centerView.frame
frame.origin.x = view.bounds.size.width
UIView.animate(withDuration: kDPDrawerControllerAnimationDuration / 2.0, animations: {
self.centerView.frame = frame
}, completion: { _ in
done?()
self.rightClosing(animated: true)
})
}
private func resetCenterViewController(_ viewController: DPCenterContentViewController) {
centerContentViewController?.willMove(toParent: nil)
DPSlideMenuManager.shared.setDrawer(drawer: nil)
centerContentViewController?.view.removeFromSuperview()
centerContentViewController?.removeFromParent()
// Set the new center view controller
centerContentViewController = viewController
DPSlideMenuManager.shared.setDrawer(drawer: self)
// Add the new center view controller to the container
addCenterViewController()
}
func replaceCenterViewController(_ centerContentViewController: DPCenterContentViewController,
menuPosition: MenuPosition) {
switch menuPosition {
case .left:
leftWillClose()
resetCenterViewController(centerContentViewController)
leftClosing(animated: true)
case .right:
rightWillClose()
resetCenterViewController(centerContentViewController)
rightClosing(animated: true)
}
}
// MARK: Screen rotation
override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { _ in
switch self.drawerState {
case .leftOpen:
self.leftResetViewPosition(state: .leftOpen)
case .rightOpen:
self.rightResetViewPosition(state: .rightOpen)
case .closed:
self.leftMenuViewController?.resetUI()
self.rightMenuViewController?.resetUI()
default:
break
}
}
}
private func leftResetViewPosition(state: DrawerControllerState) {
guard state == .leftOpen else { return }
let leftViewFinalFrame = view.bounds
var centerViewFinalFrame = view.bounds
centerViewFinalFrame.origin.x = UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset
centerView.frame = centerViewFinalFrame
leftView.frame = leftViewFinalFrame
}
private func rightResetViewPosition(state: DrawerControllerState) {
guard state == .rightOpen else { return }
var rightViewFinalFrame = view.bounds
rightViewFinalFrame.origin.x = kDPDrawerControllerDrawerWidthGapOffset
rightView.frame = rightViewFinalFrame
}
}
|
1644513febf3a729cabe3cf356e636e2
| 34.641026 | 117 | 0.688489 | false | false | false | false |
chenchangqing/travelMapMvvm
|
refs/heads/master
|
travelMapMvvm/travelMapMvvm/Views/Controllers/VerifyViewController.swift
|
apache-2.0
|
1
|
//
// VerifyViewController.swift
// travelMap
//
// Created by green on 15/6/18.
// Copyright (c) 2015年 com.city8. All rights reserved.
//
import UIKit
import ReactiveCocoa
class VerifyViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var view1: UIView!
@IBOutlet weak var view2: UIView!
@IBOutlet weak var view3: UIView!
@IBOutlet weak var submitBtn: UIButton!
@IBOutlet weak var verifyCodeF: UITextField!
@IBOutlet weak var passwordF: UITextField!
@IBOutlet weak var timeB: UIButton!
@IBOutlet weak var timeL: UILabel!
// 在获取验证码后跳转时,请赋值
var verifyViewModel:VerifyViewModel!
// 校验信号
var isValidVerifyCodeSignal:RACSignal!
var isValidPwdSignal:RACSignal!
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
// 初始化
setup()
}
// MARK: - setup
private func setup() {
setupAllUIStyle()
setupSignals()
setupTextFields()
setupRegisterButton()
setupMessage()
bindViewModel()
setupCommands()
}
/**
* 设置UIStyle
*/
private func setupAllUIStyle() {
view1.loginRadiusStyle()
view2.loginRadiusStyle()
view3.loginRadiusStyle()
submitBtn.loginNoBorderStyle()
}
/**
* 校验信号设置
*/
private func setupSignals() {
// 验证码是否有效信号
isValidVerifyCodeSignal = verifyCodeF.rac_textSignal().mapAs {
(text: NSString) -> NSNumber in
return ValidHelper.isValidVerifyCode(text)
}
// 密码是否有效信号
isValidPwdSignal = passwordF.rac_textSignal().mapAs({ (text:NSString) -> NSNumber in
return ValidHelper.isValidPassword(text)
})
}
/**
* 文本输入设置
*/
private func setupTextFields() {
// 绑定验证输入框背景色
isValidVerifyCodeSignal.mapAs { (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIColor.clearColor() : UITextField.warningBackgroundColor
}.skip(1) ~> RAC(self.verifyCodeF,"backgroundColor")
// 绑定密码输入框背景色
isValidPwdSignal.mapAs { (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIColor.clearColor() : UITextField.warningBackgroundColor
}.skip(1) ~> RAC(self.passwordF,"backgroundColor")
}
/**
* 注册、发送验证按钮设置
*/
private func setupRegisterButton() {
let tempSignal = RACSignal.combineLatest([
isValidVerifyCodeSignal,
isValidPwdSignal,
self.verifyViewModel.commitVerifyCodeCommand.executing,
self.verifyViewModel.registerUserCommand.executing,
self.verifyViewModel.registerViewModel.sendVerityCodeCommand.executing
]).mapAs({ (tuple: RACTuple) -> NSNumber in
let first = tuple.first as! Bool
let second = tuple.second as! Bool
let third = tuple.third as! Bool
let fourth = tuple.fourth as! Bool
let fifth = tuple.fifth as! Bool
let enabled = first && second && !third && !fourth && !fifth
return enabled
})
tempSignal ~> RAC(submitBtn,"enabled")
tempSignal.mapAs { (enabled:NSNumber) -> UIColor in
return enabled.boolValue ? UIButton.defaultBackgroundColor : UIButton.enabledBackgroundColor
} ~> RAC(submitBtn,"backgroundColor")
// 事件
submitBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.view.endEditing(true)
self.verifyViewModel.commitVerifyCodeCommand.execute(nil)
}
timeB.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { (any:AnyObject!) -> Void in
self.view.endEditing(true)
self.verifyViewModel.registerViewModel.sendVerityCodeCommand.execute(nil)
}
}
/**
* 提示设置
*/
private func setupMessage() {
RACSignal.combineLatest([
self.verifyViewModel.commitVerifyCodeCommand.executing,
self.verifyViewModel.registerUserCommand.executing,
self.verifyViewModel.registerViewModel.sendVerityCodeCommand.executing
,RACObserve(self.verifyViewModel, "msg")
]).subscribeNextAs { (tuple: RACTuple) -> () in
let isLoading = tuple.first as! Bool || tuple.second as! Bool || tuple.third as! Bool
let msg = tuple.fourth as! String
if isLoading {
self.showHUDIndicator()
} else {
if msg.isEmpty {
self.hideHUD()
}
}
if !msg.isEmpty {
self.showHUDErrorMessage(msg)
}
}
}
/**
* 绑定View model
*/
private func bindViewModel() {
// 时时更新loginViewModel的验证码、密码
verifyCodeF.rac_textSignal() ~> RAC(self.verifyViewModel, "verifyCode")
passwordF.rac_textSignal() ~> RAC(self.verifyViewModel, "password")
// 绑定时间按钮、text信息
RACObserve(self.verifyViewModel, "timeButtonHidden") ~> RAC(self.timeB,"hidden")
RACObserve(self.verifyViewModel, "timeLableText") ~> RAC(self.timeL,"text")
RACObserve(self.verifyViewModel, "timeLableTextHidden") ~> RAC(self.timeL,"hidden")
}
/**
* 命令设置
*/
private func setupCommands() {
// 验证验证码命令设置
self.verifyViewModel.commitVerifyCodeCommand.executionSignals.subscribeNextAs { (signal:RACSignal) -> () in
signal.dematerialize().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNext({ (any:AnyObject!) -> Void in
}, error: { (error:NSError!) -> Void in
self.verifyViewModel.msg = error.localizedDescription
}, completed: { () -> Void in
// 执行注册命令
self.verifyViewModel.msg = kMsgCheckVerifyCodeSuccess
self.verifyViewModel.registerUserCommand.execute(nil)
})
}
// 手机注册命令设置
self.verifyViewModel.registerUserCommand.executionSignals.subscribeNextAs { (signal:RACSignal) -> () in
signal.dematerialize().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNext({ (any:AnyObject!) -> Void in
}, error: { (error:NSError!) -> Void in
self.verifyViewModel.msg = error.localizedDescription
}, completed: { () -> Void in
// 执行跳转
self.verifyViewModel.msg = kMsgRegisterSuccess
self.performSegueWithIdentifier(kSegueFromVerifyViewControllerToLoginViewController, sender: nil)
})
}
// 重发验证码命令设置
self.verifyViewModel.registerViewModel.sendVerityCodeCommand.executionSignals.subscribeNextAs { (signal:RACSignal) -> () in
signal.dematerialize().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNext({ (any:AnyObject!) -> Void in
}, error: { (error:NSError!) -> Void in
if let error = error as? SMS_SDKError {
self.verifyViewModel.msg = "\(error.code),\(error.errorDescription)"
} else {
self.verifyViewModel.msg = error.localizedDescription
}
}, completed: { () -> Void in
// 提示发送成功
self.verifyViewModel.msg = kMsgSendVerifyCodeSuccess
})
}
}
}
|
80b7a699027ebd4ea1d3eef3119c5f87
| 31.170635 | 131 | 0.55779 | false | false | false | false |
apple/swift-syntax
|
refs/heads/main
|
Tests/SwiftSyntaxBuilderTest/VariableTests.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
import XCTest
import SwiftSyntax
import SwiftSyntaxBuilder
final class VariableTests: XCTestCase {
func testVariableDecl() {
let leadingTrivia = Trivia.unexpectedText("␣")
let buildable = VariableDecl(leadingTrivia: leadingTrivia, letOrVarKeyword: .let) {
PatternBinding(pattern: Pattern("a"), typeAnnotation: TypeAnnotation(type: ArrayType(elementType: Type("Int"))))
}
AssertBuildResult(buildable, "␣let a: [Int]")
}
func testVariableDeclWithValue() {
let leadingTrivia = Trivia.unexpectedText("␣")
let buildable = VariableDecl(leadingTrivia: leadingTrivia, letOrVarKeyword: .var) {
PatternBinding(
pattern: Pattern("d"),
typeAnnotation: TypeAnnotation(type: DictionaryType(keyType: Type("String"), valueType: Type("Int"))),
initializer: InitializerClause(value: DictionaryExpr()))
}
AssertBuildResult(buildable, "␣var d: [String: Int] = [: ]")
}
func testVariableDeclWithExplicitTrailingCommas() {
let buildable = VariableDecl(letOrVarKeyword: .let, bindings: [
PatternBinding(pattern: Pattern("a"), initializer: InitializerClause(value: ArrayExpr(
leftSquare: .`leftSquareBracket`.withTrailingTrivia(.newline)) {
for i in 1...3 {
ArrayElement(
expression: IntegerLiteralExpr(i),
trailingComma: .comma.withTrailingTrivia(.newline)
)
}
}
))
])
AssertBuildResult(buildable, """
let a = [
1,
2,
3,
]
""")
}
func testMultiPatternVariableDecl() {
let buildable = VariableDecl(letOrVarKeyword: .let) {
PatternBinding(pattern: Pattern("a"), initializer: InitializerClause(value: ArrayExpr {
for i in 1...3 {
ArrayElement(expression: IntegerLiteralExpr(i))
}
}))
PatternBinding(pattern: Pattern("d"), initializer: InitializerClause(value: DictionaryExpr {
for i in 1...3 {
DictionaryElement(keyExpression: StringLiteralExpr(content: "key\(i)"), valueExpression: IntegerLiteralExpr(i))
}
}))
PatternBinding(pattern: Pattern("i"), typeAnnotation: TypeAnnotation(type: Type("Int")))
PatternBinding(pattern: Pattern("s"), typeAnnotation: TypeAnnotation(type: Type("String")))
}
AssertBuildResult(buildable, #"let a = [1, 2, 3], d = ["key1": 1, "key2": 2, "key3": 3], i: Int, s: String"#)
}
func testClosureTypeVariableDecl() {
let type = FunctionType(arguments: [TupleTypeElement(type: Type("Int"))], returnType: Type("Bool"))
let buildable = VariableDecl(letOrVarKeyword: .let) {
PatternBinding(pattern: Pattern("c"), typeAnnotation: TypeAnnotation(type: type))
}
AssertBuildResult(buildable, "let c: (Int) -> Bool")
}
func testComputedProperty() {
let buildable = VariableDecl(name: "test", type: TypeAnnotation(type: Type("Int"))) {
SequenceExpr {
IntegerLiteralExpr(4)
BinaryOperatorExpr(text: "+")
IntegerLiteralExpr(5)
}
}
AssertBuildResult(buildable, """
var test: Int {
4 + 5
}
""")
}
func testAttributedVariables() {
let testCases: [UInt: (VariableDecl, String)] = [
#line: (
VariableDecl(
attributes: AttributeList { CustomAttribute("Test") },
.var,
name: "x",
type: TypeAnnotation(type: Type("Int"))
),
"""
@Test var x: Int
"""
),
#line: (
VariableDecl(
attributes: AttributeList { CustomAttribute("Test")} ,
name: "y",
type: TypeAnnotation(type: Type("String"))
) {
StringLiteralExpr(content: "Hello world!")
},
"""
@Test var y: String {
"Hello world!"
}
"""
),
#line: (
VariableDecl(
attributes: AttributeList { CustomAttribute("WithArgs") {
TupleExprElement(expression: "value1")
TupleExprElement(label: "label", expression: "value2")
} },
name: "z",
type: TypeAnnotation(type: Type("Float"))
) {
FloatLiteralExpr(0.0)
},
"""
@WithArgs(value1, label: value2) var z: Float {
0.0
}
"""
),
#line: (
VariableDecl(
attributes: AttributeList { CustomAttribute("WithArgs") {
TupleExprElement(expression: "value")
} },
modifiers: [DeclModifier(name: .public)],
.let,
name: "z",
type: TypeAnnotation(type: Type("Float"))
),
"""
@WithArgs(value) public let z: Float
"""
),
]
for (line, testCase) in testCases {
let (builder, expected) = testCase
AssertBuildResult(builder, expected, line: line)
}
}
}
|
4a961f2560ed3c32b25440beac83600f
| 30.635294 | 121 | 0.578096 | false | true | false | false |
adamcin/SwiftCJ
|
refs/heads/master
|
SwiftCJ/CJDataElem.swift
|
mit
|
1
|
import Foundation
public struct CJDataElem {
public let name: String
public let prompt: String?
public let value: AnyObject?
func copyAndSet(value: AnyObject?) -> CJDataElem {
if value == nil {
return CJDataElem(name: name, prompt: prompt, value: nil)
} else if NSJSONSerialization.isValidJSONObject(value!) {
return CJDataElem(name: name, prompt: prompt, value: value!)
} else {
return CJDataElem(name: name, prompt: prompt, value: "\(value!)")
}
}
func toSeri() -> [String: AnyObject] {
var seri = [String: AnyObject]()
seri["name"] = self.name
if let prompt = self.prompt {
seri["prompt"] = self.prompt
}
if let value: AnyObject = self.value {
seri["value"] = self.value
}
return seri
}
static func elementFromDictionary(dict: [NSObject: AnyObject]) -> CJDataElem? {
if let name = dict["name"] as? String {
let prompt = dict["prompt"] as? String
let value: AnyObject? = dict["value"]
return CJDataElem(name: name, prompt: prompt, value: value)
}
return nil
}
}
|
8fc7765dacebd6685e2e26491511c797
| 31.210526 | 83 | 0.564542 | false | false | false | false |
ArnavChawla/InteliChat
|
refs/heads/master
|
Carthage/Checkouts/ios-sdk/Source/TextToSpeechV1/Models/CustomVoiceUpdate.swift
|
apache-2.0
|
3
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** A custom voice model used by the Text to Speech service. */
public struct CustomVoiceUpdate: JSONEncodable {
/// The new name for the custom voice model.
private let name: String?
/// The new description for the custom voice model.
private let description: String?
/// A list of words and their translations from the custom voice model.
private let words: [Word]
/// Used to initialize a `CustomVoiceUpdate` model.
public init(name: String? = nil, description: String? = nil, words: [Word] = []) {
self.name = name
self.description = description
self.words = words
}
/// Used internally to serialize a `CustomVoiceUpdate` model to JSON.
public func toJSONObject() -> Any {
var json = [String: Any]()
if let name = name {
json["name"] = name
}
if let description = description {
json["description"] = description
}
json["words"] = words.map { word in word.toJSONObject() }
return json
}
}
|
c45349f1b85fbf1b3a26cde47c33be67
| 31.884615 | 86 | 0.652632 | false | false | false | false |
pennlabs/penn-mobile-ios
|
refs/heads/main
|
PennMobile/Home/Fitness/Cells/FitnessHeaderView.swift
|
mit
|
1
|
//
// FitnessHeaderView.swift
// PennMobile
//
// Created by Dominic Holmes on 9/2/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import UIKit
class FitnessHeaderView: UITableViewHeaderFooterView {
static let headerHeight: CGFloat = 60
static let identifier = "fitnessHeaderView"
var label: UILabel = {
let label = UILabel()
label.font = .primaryTitleFont
label.textColor = .labelPrimary
label.textAlignment = .left
return label
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .uiBackground
addSubview(label)
_ = label.anchor(nil, left: leftAnchor, bottom: bottomAnchor, right: nil, topConstant: 0, leftConstant: 28, bottomConstant: 10, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
acab9f100814d2f2f6926cb68afbddf4
| 26.777778 | 190 | 0.674 | false | false | false | false |
nalexn/ViewInspector
|
refs/heads/master
|
Sources/ViewInspector/SwiftUI/Gesture.swift
|
mit
|
1
|
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public protocol GestureViewType {
associatedtype T: SwiftUI.Gesture & Inspectable
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct Gesture<T>: KnownViewType, GestureViewType
where T: SwiftUI.Gesture & Inspectable {
public static var typePrefix: String {
return Inspector.typeName(type: T.self, generics: .remove)
}
public static var namespacedPrefixes: [String] {
var prefixes = [
"SwiftUI.AddGestureModifier",
"SwiftUI.HighPriorityGestureModifier",
"SwiftUI.SimultaneousGestureModifier",
"SwiftUI._ChangedGesture",
"SwiftUI._EndedGesture",
"SwiftUI._MapGesture",
"SwiftUI._ModifiersGesture",
"SwiftUI.GestureStateGesture"
]
prefixes.append(Inspector.typeName(type: T.self, namespaced: true, generics: .remove))
return prefixes
}
public static func inspectionCall(call: String, typeName: String, index: Int? = nil) -> String {
if let index = index {
return "\(call)(\(typeName.self).self, \(index))"
} else {
return "\(call)(\(typeName.self).self)"
}
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension Gesture where Self: Inspectable {
var entity: Content.InspectableEntity { .gesture }
func extractContent(environmentObjects: [AnyObject]) throws -> Any { () }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension AnyGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
extension DragGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ExclusiveGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, tvOS 14.0, *)
extension LongPressGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension MagnificationGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
extension RotationGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension SequenceGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension SimultaneousGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, tvOS 16.0, *)
extension TapGesture: Inspectable {}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func gesture<T>(_ type: T.Type, _ index: Int? = nil) throws -> InspectableView<ViewType.Gesture<T>>
where T: Gesture & Inspectable {
return try gestureModifier(
modifierName: "AddGestureModifier", path: "modifier",
type: type, call: "gesture", index: index)
}
func highPriorityGesture<T>(_ type: T.Type, _ index: Int? = nil) throws -> InspectableView<ViewType.Gesture<T>>
where T: Gesture & Inspectable {
return try gestureModifier(
modifierName: "HighPriorityGestureModifier", path: "modifier",
type: type, call: "highPriorityGesture", index: index)
}
func simultaneousGesture<T>(_ type: T.Type, _ index: Int? = nil) throws -> InspectableView<ViewType.Gesture<T>>
where T: Gesture & Inspectable {
return try gestureModifier(
modifierName: "SimultaneousGestureModifier", path: "modifier",
type: type, call: "simultaneousGesture", index: index)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View: GestureViewType {
func first<G: Gesture>(_ type: G.Type) throws -> InspectableView<ViewType.Gesture<G>> {
return try gestureFromComposedGesture(type, .first)
}
func second<G: Gesture>(_ type: G.Type) throws -> InspectableView<ViewType.Gesture<G>> {
return try gestureFromComposedGesture(type, .second)
}
func gestureMask() throws -> GestureMask {
return try Inspector.attribute(
path: "gestureMask", value: content.view, type: GestureMask.self)
}
func callUpdating<Value, State>(
value: Value,
state: inout State,
transaction: inout Transaction) throws {
typealias Callback = (Value, inout State, inout Transaction) -> Void
let callbacks = try gestureCallbacks(
name: "GestureStateGesture", path: "body",
type: Callback.self, call: "updating")
for callback in callbacks {
callback(value, &state, &transaction)
}
}
func callOnChanged<Value>(value: Value) throws {
typealias Callback = (Value) -> Void
let callbacks = try gestureCallbacks(
name: "_ChangedGesture", path: "_body|modifier|callbacks|changed",
type: Callback.self, call: "onChanged")
for callback in callbacks {
callback(value)
}
}
func callOnEnded<Value>(value: Value) throws {
typealias Callback = (Value) -> Void
let callbacks = try gestureCallbacks(
name: "_EndedGesture", path: "_body|modifier|callbacks|ended",
type: Callback.self, call: "onEnded")
for callback in callbacks {
callback(value)
}
}
func actualGesture() throws -> View.T {
let typeName = Inspector.typeName(type: View.T.self)
let valueName = Inspector.typeName(value: content.view)
let (_, modifiers) = gestureInfo(typeName, valueName)
if modifiers.count > 0 {
let path = modifiers.reduce("") { return addSegment(knownGestureModifier($1)!, to: $0) }
return try Inspector.attribute(path: path, value: content.view, type: View.T.self)
}
return try Inspector.cast(value: content.view, type: View.T.self)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
@available(macOS 10.15, *)
@available(iOS, unavailable)
@available(tvOS, unavailable)
func gestureModifiers<T>() throws -> EventModifiers
where T: Gesture & Inspectable, View == ViewType.Gesture<T> {
let typeName = Inspector.typeName(type: T.self)
let valueName = Inspector.typeName(value: content.view)
let (_, modifiers) = gestureInfo(typeName, valueName)
let result = try modifiers.reduce((path: "", eventModifiers: EventModifiers())) { result, modifier in
var eventModifiers = result.eventModifiers
if modifier == "_ModifiersGesture" {
let value = try Inspector.attribute(
path: addSegment("_body|modifier|modifiers|rawValue", to: result.path),
value: content.view,
type: Int.self)
eventModifiers.formUnion(EventModifiers.init(rawValue: value))
}
return (path: addSegment(knownGestureModifier(modifier)!, to: result.path), eventModifiers: eventModifiers)
}
return result.eventModifiers
}
}
// MARK: - Private
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension InspectableView {
func gestureModifier<T>(
modifierName: String,
path: String,
type: T.Type,
call: String,
index: Int? = nil) throws -> InspectableView<ViewType.Gesture<T>>
where T: Gesture, T: Inspectable {
let typeName = Inspector.typeName(type: type)
let modifierCall = ViewType.Gesture<T>.inspectionCall(call: call, typeName: typeName, index: nil)
let rootView = try modifierAttribute(modifierName: modifierName, path: path, type: Any.self,
call: modifierCall, index: index ?? 0)
let (name, _) = gestureInfo(typeName, Inspector.typeName(value: rootView))
guard name == typeName else {
throw InspectionError.typeMismatch(factual: name, expected: typeName)
}
return try InspectableView<ViewType.Gesture<T>>.init(
Content(rootView), parent: self,
call: ViewType.Gesture<T>.inspectionCall(call: call, typeName: typeName, index: index))
}
enum GestureOrder {
case first
case second
}
func gestureFromComposedGesture<T: Gesture>(
_ type: T.Type,
_ order: GestureOrder) throws -> InspectableView<ViewType.Gesture<T>> {
let valueName = Inspector.typeName(value: content.view)
let typeName = Inspector.typeName(type: type)
let (name1, modifiers1) = gestureInfo(typeName, valueName)
guard isComposedGesture(name1) else {
throw InspectionError.typeMismatch(
factual: name1,
expected: "ExclusiveGesture, SequenceGesture, or SimultaneousGesture")
}
var path = modifiers1.reduce("") { addSegment(knownGestureModifier($1)!, to: $0) }
let call: String
switch order {
case .first:
path = addSegment("first", to: path)
call = ViewType.Gesture<T>.inspectionCall(call: "first", typeName: typeName)
case .second:
path = addSegment("second", to: path)
call = ViewType.Gesture<T>.inspectionCall(call: "second", typeName: typeName)
}
let rootView = try Inspector.attribute(path: path, value: content.view)
let (name2, _) = gestureInfo(typeName, Inspector.typeName(value: rootView))
let gestureTypeName = Inspector.typeName(type: type)
guard name2 == gestureTypeName else {
throw InspectionError.typeMismatch(factual: name2, expected: gestureTypeName)
}
return try .init(Inspector.unwrap(content: Content(rootView)), parent: self, call: call)
}
func gestureCallbacks<T>(
name: String,
path callbackPath: String,
type: T.Type,
call: String) throws -> [T] {
let valueName = Inspector.typeName(value: content.view)
let typeName = Inspector.typeName(type: type)
let (_, modifiers) = gestureInfo(typeName, valueName)
let result = try modifiers.reduce((path: "", callbacks: [T]())) { result, modifier in
var callbacks = result.callbacks
if modifier == name {
let object = try Inspector.attribute(
path: addSegment(callbackPath, to: result.path),
value: content.view,
type: T.self)
callbacks.append(object)
}
return (path: addSegment(knownGestureModifier(modifier)!, to: result.path), callbacks: callbacks)
}
if result.callbacks.count == 0 {
throw InspectionError.callbackNotFound(
parent: Inspector.typeName(value: content.view),
callback: call)
}
return result.callbacks.reversed()
}
typealias GestureInfo = (name: String, modifiers: [String])
func gestureInfo(_ name: String, _ valueName: String) -> GestureInfo {
var modifiers = parseModifiers(valueName)
return gestureInfo(name, &modifiers)
}
func gestureInfo(_ name: String, _ modifiers: inout [String]) -> GestureInfo {
let modifier = modifiers.removeLast()
if let gestureClass = knownGesture(modifier) {
switch gestureClass {
case .simple:
return (modifier, [])
case .composed:
return traverseComposedGesture(modifier, name, &modifiers)
case .state :
return traverseStateGesture(modifier, name, &modifiers)
}
} else if modifier == name {
return (modifier, [])
} else if knownGestureModifier(modifier) != nil {
let result = gestureInfo(name, &modifiers)
return (result.0, [modifier] + result.1)
}
return (name, modifiers)
}
func parseModifiers(_ name: String) -> [String] {
let separators = CharacterSet(charactersIn: "<>, ")
return name
.components(separatedBy: separators)
.compactMap { $0 == "" ? nil : $0 }
.reversed()
}
func traverseComposedGesture(_ modifier: String, _ name: String,
_ modifiers: inout [String]) -> GestureInfo {
let (first, _) = gestureInfo(name, &modifiers)
let (second, _) = gestureInfo(name, &modifiers)
return ("\(modifier)<\(first), \(second)>", [])
}
func traverseStateGesture(_ modifier: String, _ name: String,
_ modifiers: inout [String]) -> GestureInfo {
let result = gestureInfo(name, &modifiers)
_ = modifiers.popLast()
return (result.0, [modifier] + result.1)
}
func addSegment(_ segment: String, to path: String) -> String {
return (path == "") ? segment : path + "|" + segment
}
enum GestureClass {
case simple
case composed
case state
}
func knownGesture(_ name: String) -> GestureClass? {
let knownGestures: [String: GestureClass] = [
"DragGesture": .simple,
"ExclusiveGesture": .composed,
"GestureStateGesture": .state,
"LongPressGesture": .simple,
"MagnificationGesture": .simple,
"RotationGesture": .simple,
"SequenceGesture": .composed,
"SimultaneousGesture": .composed,
"TapGesture": .simple,
]
return knownGestures[name]
}
func knownGestureModifier(_ name: String) -> String? {
let knownGestureModifiers: [String: String] = [
"AddGestureModifier": "gesture",
"HighPriorityGestureModifier": "gesture",
"SimultaneousGestureModifier": "gesture",
"_ChangedGesture": "_body|content",
"_EndedGesture": "_body|content",
"_MapGesture": "_body|content",
"_ModifiersGesture": "_body|content",
"GestureStateGesture": "base",
"Optional": "some",
]
return knownGestureModifiers[name]
}
func isComposedGesture(_ name: String) -> Bool {
let parts = parseModifiers(name)
return knownGesture(parts.last!) == .composed
}
}
// MARK: - Gesture Value initializers
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
public extension DragGesture.Value {
private struct Allocator {
var time: Date
var location: CGPoint
var startLocation: CGPoint
var velocity: CGVector
}
init(time: Date, location: CGPoint, startLocation: CGPoint, velocity: CGVector) {
self = unsafeBitCast(
Allocator(
time: time,
location: location,
startLocation: startLocation,
velocity: velocity),
to: DragGesture.Value.self
)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 14.0, *)
public extension LongPressGesture.Value {
private struct Allocator {
var finished: Bool
}
init(finished: Bool) {
self = unsafeBitCast(
Allocator(finished: finished),
to: LongPressGesture.Value.self
)
}
}
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public extension MagnificationGesture.Value {
private struct Allocator {
var magnifyBy: CGFloat
}
init(magnifyBy: CGFloat) {
self = unsafeBitCast(
Allocator(magnifyBy: magnifyBy),
to: MagnificationGesture.Value.self
)
}
}
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public extension RotationGesture.Value {
private struct Allocator {
var angle: Angle
}
init(angle: Angle) {
self = unsafeBitCast(
Allocator(angle: angle),
to: RotationGesture.Value.self
)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension SimultaneousGesture.Value {
private struct Allocator {
var first: First.Value?
var second: Second.Value?
}
init(first: First.Value?, second: Second.Value?) {
self = unsafeBitCast(
Allocator(first: first, second: second),
to: SimultaneousGesture.Value.self)
}
}
|
f21099b44da5a5db205dab33eb8fcd5c
| 34.611111 | 119 | 0.602544 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Sources/Networking/ElloProviderErrors.swift
|
mit
|
1
|
////
/// ElloProviderErrors.swift
//
extension ElloProvider {
static func generateElloError(_ data: Data, statusCode: Int?) -> NSError {
var elloNetworkError: ElloNetworkError?
if let dictJSONDecoded = try? JSONSerialization.jsonObject(with: data),
let dictJSON = dictJSONDecoded as? [String: Any],
let node = dictJSON[MappingType.errorsType.rawValue] as? [String: Any]
{
elloNetworkError = Mapper.mapToObject(node, type: .errorType) as? ElloNetworkError
}
let errorCodeType: ElloErrorCode = statusCode.map { .statusCode($0) } ?? .data
return NSError.networkError(elloNetworkError, code: errorCodeType)
}
static func failedToMapObjects(_ reject: ErrorBlock) {
let jsonMappingError = ElloNetworkError(
attrs: nil,
code: ElloNetworkError.CodeType.unknown,
detail: "Failed to map objects",
messages: nil,
status: nil,
title: "Failed to map objects"
)
let elloError = NSError.networkError(jsonMappingError, code: .jsonMapping)
reject(elloError)
}
}
|
9202579ba22ee7f697dee3d0c0cef231
| 35.0625 | 94 | 0.635182 | false | false | false | false |
reuterm/CalendarAPI
|
refs/heads/master
|
iOS Frontend/Calendar/EventTableViewController.swift
|
mit
|
1
|
//
// EventTableViewController.swift
// Calendar
//
// Created by Max Reuter on 20/11/15.
// Copyright © 2015 reuterm. All rights reserved.
//
import UIKit
//import EventKit
class EventTableViewController: UITableViewController {
// MARK: Properties
var events = [Event]()
override func viewDidLoad() {
super.viewDidLoad()
// Use edit button provided by table view controller
navigationItem.leftBarButtonItem = editButtonItem()
self.navigationController!.toolbarHidden = false;
// Retrieve events
getEvents()
self.refreshControl = UIRefreshControl()
self.refreshControl!.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl!.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refreshControl!)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "EventTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EventTableViewCell
// Fetch events appropriate event from data source layout
let event = events[indexPath.row]
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
formatter.timeStyle = .ShortStyle
cell.titleLabel.text = event.title
cell.dateLabel.text = "Starting: \(formatter.stringFromDate(event.start))"
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
deleteEvent(events[indexPath.row])
events.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditEvent" {
let eventEditViewController = segue.destinationViewController as! EventViewController
// Get the event cell that generated the segue
if let selectedEventCell = sender as? EventTableViewCell {
let indexPath = tableView.indexPathForCell(selectedEventCell)!
let selectedEvent = events[indexPath.row]
eventEditViewController.event = selectedEvent
}
} else if segue.identifier == "AddEvent" {
}
}
@IBAction func unwindToEventList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? EventViewController, event = sourceViewController.event {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update existing event
events[selectedIndexPath.row] = event
tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
updateEvent(event)
} else {
// Add new event
let newIndexPath = NSIndexPath(forRow: events.count, inSection: 0)
events.append(event)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
addEvent(event)
}
}
}
// MARK: Actions
// @IBAction func importEvents(sender: UIBarButtonItem) {
//
// let eventStore = EKEventStore()
//
// switch EKEventStore.authorizationStatusForEntityType(.Event) {
// case .Authorized:
// fetchEvents(eventStore)
// case .Denied:
// print("Access denied")
// case .NotDetermined:
//
// eventStore.requestAccessToEntityType(.Event, completion:
// {[weak self] (granted: Bool, error: NSError?) -> Void in
// if granted {
// self!.fetchEvents(eventStore)
// } else {
// print("Access denied")
// }
// })
// default:
// print("Case Default")
// }
//
// }
// MARK: REST Calls
func refresh(sender:AnyObject) {
getEvents()
self.refreshControl?.endRefreshing()
}
func getEvents() {
// Setup the session to make REST GET call.
let endpoint: String = "http://localhost:8080/api/events/"
let session = NSURLSession.sharedSession()
let url = NSURL(string: endpoint)!
session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure we get an OK response
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
// Read the JSON
do {
if let _ = NSString(data:data!, encoding: NSUTF8StringEncoding) {
// Parse JSON from API
let jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
// print(jsonArray)
// Configure date formatter to parse ISO8601 date format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
// dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
var tmp = [Event]()
// Parse JSON object
for item in jsonArray {
let event = item as! NSDictionary
let id = event["_id"] as! String
let title = event["title"] as! String
let description = event["description"] as! String
let startString = event["start"] as! String
let endString = event["end"] as! String
let venue = event["venue"] as! String
// Unwrap optionals
let start = dateFormatter.dateFromString(startString)!
let end = dateFormatter.dateFromString(endString)!
tmp.append(Event(id: id, title: title, description: description, start: start, end: end, venue: venue))
}
self.events = tmp
// Reload table
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
} catch {
print("Error converting response!")
}
}).resume()
}
func addEvent(event: Event) {
// Set up date format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// Set up the session to make REST POST call
let postEndpoint: String = "http://localhost:8080/api/events/"
let url = NSURL(string: postEndpoint)!
let session = NSURLSession.sharedSession()
let postParams : [String: AnyObject] = ["title": event.title, "description": event.description, "start": dateFormatter.stringFromDate(event.start), "end": dateFormatter.stringFromDate(event.end), "venue": event.venue]
// Create the request
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions())
print("#############POST Params#############")
print(postParams)
} catch {
print("Could not create HTTP request")
}
// Make the POST call and handle it in a completion handler
session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure everything is OK
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
// Read the JSON
do {
if let postResponse = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String {
// Print respone
print("#############POST Response#############")
print("POST: " + postResponse)
// Parse the JSON to get the id
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let id = jsonDictionary["_id"] as! String
event.id = id
}
} catch {
print("Could not parse response")
}
}).resume()
}
func updateEvent(event: Event) {
// Set up date format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
// Set up the session to make REST PUT call
let putEndpoint: String = "http://localhost:8080/api/events/\(event.id!)"
let url = NSURL(string: putEndpoint)!
let session = NSURLSession.sharedSession()
let putParams : [String: AnyObject] = ["title": event.title, "description": event.description, "start": dateFormatter.stringFromDate(event.start), "end": dateFormatter.stringFromDate(event.end), "venue": event.venue]
// Create the request
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "PUT"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(putParams, options: NSJSONWritingOptions())
print("#############PUT Params#############")
print(putParams)
} catch {
print("Could not create HTTP request")
}
// Make the POST call and handle it in a completion handler
session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure everything is OK
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
// Read the JSON
if let postResponse = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String {
// Print respone
print("#############PUT Response#############")
print("POST: " + postResponse)
}
}).resume()
}
func deleteEvent(event: Event) {
// Set up the session to make REST DELETE call
let deleteEndpoint: String = "http://localhost:8080/api/events/\(event.id!)"
let url = NSURL(string: deleteEndpoint)!
let session = NSURLSession.sharedSession()
// Create the request
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "DELETE"
// Make the POST call and handle it in a completion handler
session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure everything is OK
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
}).resume()
}
// MARK: Utility
// func fetchEvents(store: EKEventStore){
//
// let endDate = NSDate(timeIntervalSinceNow: 604800*4); //This is 4 weeks in seconds
// let predicate = store.predicateForEventsWithStartDate(NSDate(), endDate: endDate, calendars: nil)
//
// let fetchedEvents = NSMutableArray(array: store.eventsMatchingPredicate(predicate))
//
// for item in fetchedEvents {
// insertEvent(Event(id: nil, title: item.title!!, description: item.notes!!, start: item.startDate, end: endDate, venue: item.location!!))
// }
// }
//
// func insertEvent(event: Event) {
// // Add new event
// let newIndexPath = NSIndexPath(forRow: events.count, inSection: 0)
// events.append(event)
// tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
// addEvent(event)
// }
}
|
38acaceec163107e91a4eecace651c04
| 39.875 | 225 | 0.578437 | false | false | false | false |
hoolrory/VideoInfoViewer-iOS
|
refs/heads/master
|
VideoInfoViewer/Extensions/UIImage.swift
|
apache-2.0
|
1
|
/**
Copyright (c) 2016 Rory Hool
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
extension UIImage {
func toSquare() -> UIImage {
let contextImage: UIImage = UIImage(cgImage: self.cgImage!)
let contextSize: CGSize = contextImage.size
var posX: CGFloat
var posY: CGFloat
var cgwidth: CGFloat
var cgheight: CGFloat
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
cgwidth = contextSize.height
cgheight = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
cgwidth = contextSize.width
cgheight = contextSize.width
}
let rect: CGRect = CGRect(x: posX, y: posY, width: cgwidth, height: cgheight)
let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)!
let image: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
return image
}
func rotate(_ degrees: CGFloat) -> UIImage {
let rotatedViewBox = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
rotatedViewBox.transform = CGAffineTransform(rotationAngle: degrees * CGFloat(M_PI / 180))
let rotatedSize: CGSize = rotatedViewBox.frame.size
UIGraphicsBeginImageContext(rotatedSize)
let context = UIGraphicsGetCurrentContext()!
context.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
context.rotate(by: (degrees * CGFloat(M_PI / 180)))
context.scaleBy(x: 1.0, y: -1.0)
context.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
|
2060c4f13be2c823390fe6b4d1990ddc
| 35.549296 | 148 | 0.636994 | false | false | false | false |
Trevi-Swift/Trevi
|
refs/heads/develop
|
Sources/Utility.swift
|
apache-2.0
|
1
|
//
// Utility.swift
// Trevi
//
// Created by LeeYoseob on 2015. 11. 30..
// Copyright © 2015 Trevi Community. All rights reserved.
//
import Foundation
public let __dirname = NSFileManager.defaultManager().currentDirectoryPath
#if os(Linux)
// Wrapper for casting between AnyObject and String
public class StringWrapper {
public var string: String
public init(string: String) {
self.string = string
}
}
#endif
extension String {
public func length() -> Int {
return self.characters.count
}
public func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
public func substring(start: Int, length: Int) -> String {
return self[self.startIndex.advancedBy(start) ..< self.startIndex.advancedBy(start + length)]
}
public func getIndex(location: Int, encoding: UInt = NSUnicodeStringEncoding) -> String.Index? {
switch (encoding) {
case NSUTF8StringEncoding:
return String.Index ( utf8.startIndex.advancedBy ( location, limit: utf8.endIndex ), within: self )!
case NSUTF16StringEncoding:
return String.Index ( utf16.startIndex.advancedBy ( location, limit: utf16.endIndex ), within: self )!
case NSUnicodeStringEncoding:
return startIndex.advancedBy ( location )
default:
return nil
}
}
}
/**
- Parameter string: The string to search.
- Parameter pattern: The regular expression pattern to compile.
- Parameter options: The regular expression options that are applied to the expression during matching. See NSRegularExpressionOptions for possible values.
- Returns: An array of tuples that include NSRange and String which are searched with regular expression.
*/
public func searchWithRegularExpression ( string: String, pattern: String, options: NSRegularExpressionOptions = [] ) -> [[String : (range: NSRange, text: String)]] {
var searched = [[String : (range: NSRange, text: String)]]()
if let regex: NSRegularExpression = try? NSRegularExpression ( pattern: pattern, options: options ) {
for matches in regex.matchesInString ( string, options: [], range: NSMakeRange( 0, string.characters.count ) ) {
var group = [String : (range: NSRange, text: String)]()
for idx in 0 ..< matches.numberOfRanges {
let range = matches.rangeAtIndex( idx )
group.updateValue((matches.rangeAtIndex(idx), string[string.startIndex.advancedBy(range.location) ..< string.startIndex.advancedBy(range.location + range.length)]), forKey: "$\(idx)")
}
searched.append(group)
}
}
return searched
}
public func getCurrentDatetime(format: String = "yyyy/MM/dd hh:mm:ss a z") -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = format
return formatter.stringFromDate(NSDate())
}
public func bridge<T : AnyObject>(obj : T) -> UnsafePointer<Void> {
return UnsafePointer(Unmanaged.passUnretained(obj).toOpaque())
}
public func bridge<T : AnyObject>(ptr : UnsafePointer<Void>) -> T {
return Unmanaged<T>.fromOpaque(COpaquePointer(ptr)).takeUnretainedValue()
}
|
e36f25e89759f844486884e41a73e363
| 36.724138 | 199 | 0.671442 | false | false | false | false |
HarukaMa/iina
|
refs/heads/master
|
iina/ISO639_2Helper.swift
|
gpl-3.0
|
1
|
//
// ISO639_2Helper.swift
// iina
//
// Created by lhc on 14/3/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
class ISO639_2Helper {
struct Language {
var code: String
var name: [String]
var description: String {
return "\(name[0]) (\(code))"
}
}
static let languages: [Language] = {
var result: [Language] = []
let filePath = Bundle.main.path(forResource: "ISO639_2", ofType: "strings")!
let dic = NSDictionary(contentsOfFile: filePath) as! [String : String]
for (k, v) in dic {
let names = v.characters.split(separator: ";").map { String($0) }
result.append(Language(code: k, name: names))
}
return result
}()
}
|
a75467179378f681c7bd42042f02b47a
| 20.117647 | 80 | 0.608635 | false | false | false | false |
tectijuana/patrones
|
refs/heads/master
|
Bloque1SwiftArchivado/PracticasSwift/CarlosGastelum/program4.swift
|
gpl-3.0
|
1
|
/*
Nombre del programa: ...................Conversiones
Creado por:............................. Carlos Gastelum Nieves
No Control: .................................................14210456
Fecha ......................................................17-02-2017
Practicas Swift del libro..............................................
*/
print("convertir p libras inglesas a s chelines a d dollares c centavos y e peniques ")
print("se convertiran 10 libras")
let libra =10
let chelin= 20
let peniq=12
let dolar=0.02
let cent=0.40
chelin = chelin*libra
peniq = peniq*chelin
dolar =dolar*chelin
centavos=centavos*dolar
print("10 libras son: \(chelines) chelines,\(peniques) peniques, \(dolares) dolares \(centavos) centavos")
|
4b626ebfc9b72f7c35e7082931500b90
| 27.461538 | 106 | 0.528796 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
validation-test/compiler_crashers_fixed/01668-swift-type-walk.swift
|
apache-2.0
|
65
|
// 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
// RUN: not %target-swift-frontend %s -typecheck
class c {
struct c) {
typealias b = B
return [B
}
extension A = h, i: A, a()
func g> {
}
}
t: (2, end)
return $0
return [1, e = a: k) -> A {
}
}
typealias E
}
convenience init(n: T) -> {
protocol c where T> : String {
print())
typealias e where T> {
}
t: (start: (p: Sequence> a {
}
public class a = 0
}
return """)-> T>() -> S : A {
typealias d.advance() -> {
return nil
}
f(m()
print()
}
}
case s: b: Int
}
return g: () {
}
protocol A {
}
}
func d.advance(n: e)
let n1: c : ()
let b = T>(A<j : a {
}
return b(x("))")
protocol e == [B<D>()
class func a(i(_ c>(Any, A<T -> <H : ExtensibleCollectionType>().b: b(start: Int -> {
f))
}
})
}
func g<e<l : [B<e: a {
func b
}
}
}
}
}
}
}
}
case b where Optional<T where T : AnyObject) {
func c: P {
default:Any, (false)
func g.A.Type) -> (""a(.B
func b, 3] == {
return [c
class C(p: () -> T) -> U -> {
return z: e<h : NSObject {}
let t: d {
protocol a {
return ""[unowned self, x {
typealias F = c: C())
class func d<T, U) -> Any, A.dynamicType)() -> T>
init()
}
class b: Boolean)
typealias g<U : P> String
}
}
(t: d {
func b[1, self.e == b.b : A, B
}
}
enum A {
var d : d = b: B<T>) -> {
}
class B = [](")
protocol A {
}
func b> [Int]].c<c
case b {
protocol C {
return nil
class A {
return nil
}
}
}
import Foundation
struct A, V, object2)
func b<H : Range<d>?
class func c() -> {
}
var d = b, AnyObj
|
81a665fe093cd4a55c0d7d7cdee3c9ad
| 14.433628 | 85 | 0.587156 | false | false | false | false |
benbahrenburg/KeyStorage
|
refs/heads/master
|
KeyStorage/Classes/KeyChainInfo.swift
|
mit
|
1
|
//
// KeyStorage - Simplifying securely saving key information
// KeyChainInfo.swift
//
// Created by Ben Bahrenburg on 3/23/16.
// Copyright © 2019 bencoding.com. All rights reserved.
//
import Foundation
import Security
/**
Contains information related to the Keychain
*/
public struct KeyChainInfo {
/**
Struct returned from getAccessGroupInfo with information related to the Keychain Group.
*/
public struct AccessGroupInfo {
/// App ID Prefix
public var prefix: String
/// Keycahin Group
public var keyChainGroup: String
/// Raw kSecAttrAccessGroup value returned from Keychain
public var rawValue: String
}
/**
Enum to used determine error details
*/
public enum errorDetail: Error {
/// No password provided or available
case noPassword
/// Incorrect data provided as part of the password return
case unexpectedPasswordData
/// Incorrect data provided for a non password Keychain item
case unexpectedItemData
/// Unknown error returned by keychain
case unhandledError(status: OSStatus)
}
/**
Enum to used map the accessibility of keychain items.
For example, if whenUnlockedThisDeviceOnly the item data can
only be accessed once the device has been unlocked after a restart.
*/
public enum accessibleOption: RawRepresentable {
case whenUnlocked,
afterFirstUnlock,
whenUnlockedThisDeviceOnly,
afterFirstUnlockThisDeviceOnly,
whenPasscodeSetThisDeviceOnly
public init?(rawValue: String) {
switch rawValue {
/**
Item data can only be accessed
while the device is unlocked. This is recommended for items that only
need be accesible while the application is in the foreground. Items
with this attribute will migrate to a new device when using encrypted
backups.
*/
case String(kSecAttrAccessibleWhenUnlocked):
self = .whenUnlocked
/**
Item data can only be
accessed once the device has been unlocked after a restart. This is
recommended for items that need to be accesible by background
applications. Items with this attribute will migrate to a new device
when using encrypted backups.
*/
case String(kSecAttrAccessibleAfterFirstUnlock):
self = .afterFirstUnlock
/**
Item data can only
be accessed while the device is unlocked. This is recommended for items
that only need be accesible while the application is in the foreground.
Items with this attribute will never migrate to a new device, so after
a backup is restored to a new device, these items will be missing.
*/
case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly):
self = .whenUnlockedThisDeviceOnly
/**
Item data can
only be accessed once the device has been unlocked after a restart.
This is recommended for items that need to be accessible by background
applications. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device these items will
be missing.
*/
case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly):
self = .afterFirstUnlockThisDeviceOnly
/**
Item data can
only be accessed while the device is unlocked. This class is only
available if a passcode is set on the device. This is recommended for
items that only need to be accessible while the application is in the
foreground. Items with this attribute will never migrate to a new
device, so after a backup is restored to a new device, these items
will be missing. No items can be stored in this class on devices
without a passcode. Disabling the device passcode will cause all
items in this class to be deleted.
*/
case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly):
self = .whenPasscodeSetThisDeviceOnly
default:
self = .afterFirstUnlockThisDeviceOnly
}
}
/// Convert Enum to String Const
public var rawValue: String {
switch self {
case .whenUnlocked:
return String(kSecAttrAccessibleWhenUnlocked)
case .afterFirstUnlock:
return String(kSecAttrAccessibleAfterFirstUnlock)
case .whenPasscodeSetThisDeviceOnly:
return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
case .whenUnlockedThisDeviceOnly:
return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
case .afterFirstUnlockThisDeviceOnly:
return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
}
}
}
}
|
d6a522e7ae8a273b7604e9be2ec33290
| 37.253425 | 92 | 0.594449 | false | false | false | false |
AlanEnjoy/Live
|
refs/heads/master
|
Live/Live/Classes/Main/View/PageContentView.swift
|
mit
|
1
|
//
// PageContentView.swift
// Live
//
// Created by Alan's Macbook on 2017/7/2.
// Copyright © 2017年 zhushuai. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int,targetIndex: Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
//MARK:- 定义属性
public var childVcs: [UIViewController]
public weak var parentViewController: UIViewController?
fileprivate var startOffsetX : CGFloat = 0
fileprivate var isForbidScrollDelegate = false
weak var delegate: PageContentViewDelegate?
//MARK:- 添加懒熟悉
public lazy var collectionView:UICollectionView = {[weak self ] in
//1.创建layout
//流水布局
let layout = UICollectionViewFlowLayout()
//设置itemsize为当前view大小
layout.itemSize = (self?.bounds.size)!
//行间距
layout.minimumLineSpacing = 0
//Item间距
layout.minimumInteritemSpacing = 0
//滚动方向
layout.scrollDirection = .horizontal
//2.创建UICollectionview
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout )
collectionView.showsHorizontalScrollIndicator = false
//分页显示
collectionView.isPagingEnabled = true
//不得超出内容的滚动区域
collectionView.bounces = false
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
collectionView.delegate = self
return collectionView
}()
//MARK:- 定义自定义构造函数
init(frame:CGRect, childVcs: [UIViewController], parentViewController: UIViewController?){
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame:frame)
//设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:- 设置UI界面
extension PageContentView {
public func setupUI() {
//1.将所有子控制器添加到父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
//2.添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
//frame等于当前bounds
collectionView.frame = bounds
}
}
//MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
//2.给Cell设置内容
//cell会循环利用,可能造成一直往控制器循环添加多遍,故需要释放不需要的cell
for view in cell.contentView.subviews{
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK:- 遵守UICollectionViewDelegate
extension PageContentView: UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//0.判断是否是点击事件
if isForbidScrollDelegate { return }
//1.定义需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
//2.判断是左滑或者右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { //左滑
//1.1 计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
//1.2 计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
//1.3 计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//1.4 完全滑过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
sourceIndex = sourceIndex - 1
}
} else { //右滑
//2.1 计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
//2.2 计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
//2.3计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count{
sourceIndex = childVcs.count - 1
}
}
//3.通知代理
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
// print("sourceIndex:\(sourceIndex),targetIndex:\(targetIndex)")
}
}
//MARK:-对外暴露的方法
extension PageContentView {
public func setCurrentIndex(currentIndex: Int){
//1.记录需要禁止执行代理方法
isForbidScrollDelegate = true
//2.滚动到合理位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x:offsetX,y: 0), animated: true)
}
}
|
4002b06dedbb59cd9aa6bf6941f20536
| 31.068571 | 124 | 0.640057 | false | false | false | false |
modulo-dm/modulo
|
refs/heads/master
|
ModuloKitTests/TestAdd.swift
|
mit
|
1
|
//
// TestAdd.swift
// modulo
//
// Created by Brandon Sneed on 2/1/16.
// Copyright © 2016 Modulo. All rights reserved.
//
import XCTest
import ELCLI
import ELFoundation
@testable import ModuloKit
class TestAdd: XCTestCase {
let modulo = Modulo()
override func setUp() {
super.setUp()
moduloReset()
print("working path = \(FileManager.workingPath())")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBasicAddModuleToModule() {
let status = Git().clone("[email protected]:modulo-dm/test-add.git", path: "test-add")
XCTAssertTrue(status == .success)
FileManager.setWorkingPath("test-add")
let result = Modulo.run(["add", "[email protected]:modulo-dm/test-add-update.git", "--version", "1.0", "-v"])
XCTAssertTrue(result == .success)
let spec = ModuleSpec.load(contentsOfFile: specFilename)
XCTAssertTrue(spec!.dependencies.count > 0)
XCTAssertTrue(spec!.dependencyForURL("[email protected]:modulo-dm/test-add-update.git") != nil)
FileManager.setWorkingPath("..")
Git().remove("test-add")
}
func testBasicAddModuleAlreadyExists() {
let status = Git().clone("[email protected]:modulo-dm/test-add.git", path: "test-add")
XCTAssertTrue(status == .success)
let status2 = Git().clone("[email protected]:modulo-dm/test-init.git", path: "test-init")
XCTAssertTrue(status2 == .success)
FileManager.setWorkingPath("test-add")
let result = Modulo.run(["add", "[email protected]:modulo-dm/test-init.git", "--version", "1.0", "-v", "--update"])
XCTAssertTrue(result == .dependencyAlreadyExists)
}
func testBasicAddModuleToModuleAndUpdate() {
let status = Git().clone("[email protected]:modulo-dm/test-add.git", path: "test-add")
XCTAssertTrue(status == .success)
FileManager.setWorkingPath("test-add")
let result = Modulo.run(["add", "[email protected]:modulo-dm/test-add-update.git", "--version", "1.0", "-v", "--update"])
XCTAssertTrue(result == .success)
let spec = ModuleSpec.load(contentsOfFile: specFilename)
XCTAssertTrue(spec!.dependencies.count > 0)
XCTAssertTrue(spec!.dependencies[2].repositoryURL == "[email protected]:modulo-dm/test-add-update.git")
XCTAssertTrue(FileManager.fileExists("../test-add-update/README.md"))
XCTAssertTrue(FileManager.fileExists("../test-dep1/README.md"))
XCTAssertTrue(FileManager.fileExists("../test-dep2/README.md"))
FileManager.setWorkingPath("..")
}
}
|
db5aaa8dfb5f9ba0b9121764267bddec
| 33.975309 | 126 | 0.61772 | false | true | false | false |
tgsala/HackingWithSwift
|
refs/heads/master
|
project27/project27/ViewController.swift
|
unlicense
|
1
|
//
// ViewController.swift
// project27
//
// Created by g5 on 3/16/16.
// Copyright © 2016 tgsala. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var currentDrawType = 0
override func viewDidLoad() {
super.viewDidLoad()
drawRectangle()
}
@IBAction func redrawTapped(sender: UIButton) {
currentDrawType += 1
if currentDrawType > 5 {
currentDrawType = 0
}
switch currentDrawType {
case 0:
drawRectangle()
case 1:
drawCircle()
case 2:
drawCheckerboard()
case 3:
drawRotatedSquares()
case 4:
drawLines()
case 5:
drawImagesAndText()
default:
break
}
}
func drawRectangle() {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 512, height: 512), false, 0)
let context = UIGraphicsGetCurrentContext()
let rectangle = CGRect(x: 0, y: 0, width: 502, height: 502)
CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextSetLineWidth(context, 10)
CGContextAddRect(context, rectangle)
CGContextDrawPath(context, .FillStroke)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = img
}
func drawCircle() {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 512, height: 512), false, 0)
let context = UIGraphicsGetCurrentContext()
let circle = CGRect(x: 0, y: 0, width: 502, height: 502)
CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextSetLineWidth(context, 10)
CGContextAddEllipseInRect(context, circle)
CGContextDrawPath(context, .FillStroke)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = img
}
func drawCheckerboard() {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 502, height: 502), false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
for row in 0 ..< 8 {
for col in 0 ..< 8 {
if row % 2 == 0 {
if col % 2 == 0 {
CGContextFillRect(context, CGRect(x: col * 64, y: row * 64, width: 64, height: 64))
}
} else {
if col % 2 == 1 {
CGContextFillRect(context, CGRect(x: col * 64, y: row * 64, width: 64, height: 64))
}
}
}
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = img
}
func drawRotatedSquares() {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 502, height: 502), false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 256, 256)
let rotations = 16
let amount = M_PI_2 / Double(rotations)
for _ in 0 ..< rotations {
CGContextRotateCTM(context, CGFloat(amount))
CGContextAddRect(context, CGRect(x: -128, y: -128, width: 256, height: 256))
}
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextStrokePath(context)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = img
}
func drawLines() {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 512, height: 512), false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 256, 256)
var first = true
var length: CGFloat = 256
for _ in 0 ..< 256 {
CGContextRotateCTM(context, CGFloat(M_PI_2))
if first {
CGContextMoveToPoint(context, length, 50)
first = false
} else {
CGContextAddLineToPoint(context, length, 50)
}
length *= 0.99
}
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextStrokePath(context)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView.image = img
}
func drawImagesAndText() {
// 1
UIGraphicsBeginImageContextWithOptions(CGSize(width: 512, height: 512), false, 0)
UIGraphicsGetCurrentContext()
// 2
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
// 3
let attrs = [
NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 36)!,
NSParagraphStyleAttributeName: paragraphStyle
]
// 4
let string: NSString = "The best-laid schemes o'\nmice an' men gang aft agley"
string.drawWithRect(CGRect(x: 32, y: 32, width: 448, height: 448),
options: .UsesLineFragmentOrigin, attributes: attrs, context: nil)
// 5
let mouse = UIImage(named: "mouse")
mouse?.drawAtPoint(CGPoint(x: 300, y: 150))
// 6
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// 7
imageView.image = img
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
1be74772b10fafd37f9517bd7f2a25e4
| 29.735 | 107 | 0.574264 | false | false | false | false |
ljubinkovicd/Lingo-Chat
|
refs/heads/master
|
Lingo Chat/DesignableUITextField.swift
|
mit
|
1
|
//
// DesignableUITextField.swift
// Lingo Chat
//
// Created by Dorde Ljubinkovic on 7/30/17.
// Copyright © 2017 Dorde Ljubinkovic. All rights reserved.
//
import UIKit
@IBDesignable
class DesignableUITextField: UITextField {
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
@IBInspectable var color: UIColor = UIColor.lightGray {
didSet {
updateView()
}
}
// Provides left padding for images
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
func updateView() {
if let image = leftImage {
leftViewMode = .always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = image
// In order for the image to use tint color, go to Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = color
leftView = imageView
} else {
leftViewMode = .never
leftView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes: [NSForegroundColorAttributeName: color])
}
override func caretRect(for position: UITextPosition) -> CGRect {
return CGRect.zero
}
}
|
791fbb570875c4b5fbcf2c1d7cecbbb6
| 27.192982 | 151 | 0.602987 | false | false | false | false |
danielgindi/ios-charts
|
refs/heads/master
|
Source/Charts/Renderers/YAxisRenderer.swift
|
apache-2.0
|
1
|
//
// YAxisRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(ChartYAxisRenderer)
open class YAxisRenderer: NSObject, AxisRenderer
{
public let viewPortHandler: ViewPortHandler
public let axis: YAxis
public let transformer: Transformer?
@objc public init(viewPortHandler: ViewPortHandler, axis: YAxis, transformer: Transformer?)
{
self.viewPortHandler = viewPortHandler
self.axis = axis
self.transformer = transformer
super.init()
}
/// draws the y-axis labels to the screen
open func renderAxisLabels(context: CGContext)
{
guard
axis.isEnabled,
axis.isDrawLabelsEnabled
else { return }
let xoffset = axis.xOffset
let yoffset = axis.labelFont.lineHeight / 2.5 + axis.yOffset
let dependency = axis.axisDependency
let labelPosition = axis.labelPosition
let xPos: CGFloat
let textAlign: TextAlignment
if dependency == .left
{
if labelPosition == .outsideChart
{
textAlign = .right
xPos = viewPortHandler.offsetLeft - xoffset
}
else
{
textAlign = .left
xPos = viewPortHandler.offsetLeft + xoffset
}
}
else
{
if labelPosition == .outsideChart
{
textAlign = .left
xPos = viewPortHandler.contentRight + xoffset
}
else
{
textAlign = .right
xPos = viewPortHandler.contentRight - xoffset
}
}
drawYLabels(context: context,
fixedPosition: xPos,
positions: transformedPositions(),
offset: yoffset - axis.labelFont.lineHeight,
textAlign: textAlign)
}
open func renderAxisLine(context: CGContext)
{
guard
axis.isEnabled,
axis.drawAxisLineEnabled
else { return }
context.saveGState()
defer { context.restoreGState() }
context.setStrokeColor(axis.axisLineColor.cgColor)
context.setLineWidth(axis.axisLineWidth)
if axis.axisLineDashLengths != nil
{
context.setLineDash(phase: axis.axisLineDashPhase, lengths: axis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if axis.axisDependency == .left
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
else
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
}
/// draws the y-labels on the specified x-position
open func drawYLabels(
context: CGContext,
fixedPosition: CGFloat,
positions: [CGPoint],
offset: CGFloat,
textAlign: TextAlignment)
{
let labelFont = axis.labelFont
let labelTextColor = axis.labelTextColor
let from = axis.isDrawBottomYLabelEntryEnabled ? 0 : 1
let to = axis.isDrawTopYLabelEntryEnabled ? axis.entryCount : (axis.entryCount - 1)
let xOffset = axis.labelXOffset
for i in from..<to
{
let text = axis.getFormattedLabel(i)
context.drawText(text,
at: CGPoint(x: fixedPosition + xOffset, y: positions[i].y + offset),
align: textAlign,
attributes: [.font: labelFont, .foregroundColor: labelTextColor])
}
}
open func renderGridLines(context: CGContext)
{
guard axis.isEnabled else { return }
if axis.drawGridLinesEnabled
{
let positions = transformedPositions()
context.saveGState()
defer { context.restoreGState() }
context.clip(to: self.gridClippingRect)
context.setShouldAntialias(axis.gridAntialiasEnabled)
context.setStrokeColor(axis.gridColor.cgColor)
context.setLineWidth(axis.gridLineWidth)
context.setLineCap(axis.gridLineCap)
if axis.gridLineDashLengths != nil
{
context.setLineDash(phase: axis.gridLineDashPhase, lengths: axis.gridLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
// draw the grid
positions.forEach { drawGridLine(context: context, position: $0) }
}
if axis.drawZeroLineEnabled
{
// draw zero line
drawZeroLine(context: context)
}
}
@objc open var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dy = self.axis.gridLineWidth
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
@objc open func drawGridLine(
context: CGContext,
position: CGPoint)
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.strokePath()
}
@objc open func transformedPositions() -> [CGPoint]
{
guard let transformer = self.transformer else { return [] }
var positions = axis.entries.map { CGPoint(x: 0.0, y: $0) }
transformer.pointValuesToPixel(&positions)
return positions
}
/// Draws the zero line at the specified position.
@objc open func drawZeroLine(context: CGContext)
{
guard
let transformer = self.transformer,
let zeroLineColor = axis.zeroLineColor
else { return }
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= axis.zeroLineWidth / 2.0
clippingRect.size.height += axis.zeroLineWidth
context.clip(to: clippingRect)
context.setStrokeColor(zeroLineColor.cgColor)
context.setLineWidth(axis.zeroLineWidth)
let pos = transformer.pixelForValues(x: 0.0, y: 0.0)
if axis.zeroLineDashLengths != nil
{
context.setLineDash(phase: axis.zeroLineDashPhase, lengths: axis.zeroLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: pos.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: pos.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
open func renderLimitLines(context: CGContext)
{
guard let transformer = self.transformer else { return }
let limitLines = axis.limitLines
guard !limitLines.isEmpty else { return }
context.saveGState()
defer { context.restoreGState() }
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for l in limitLines where l.isEnabled
{
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
guard l.drawLabelEnabled, !label.isEmpty else { continue }
let labelLineHeight = l.valueFont.lineHeight
let xOffset = 4.0 + l.xOffset
let yOffset = l.lineWidth + labelLineHeight + l.yOffset
let align: TextAlignment
let point: CGPoint
switch l.labelPosition
{
case .rightTop:
align = .right
point = CGPoint(x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset)
case .rightBottom:
align = .right
point = CGPoint(x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight)
case .leftTop:
align = .left
point = CGPoint(x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset)
case .leftBottom:
align = .left
point = CGPoint(x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight)
}
context.drawText(label,
at: point,
align: align,
attributes: [.font: l.valueFont, .foregroundColor: l.valueTextColor])
}
}
@objc open func computeAxis(min: Double, max: Double, inverted: Bool)
{
var min = min, max = max
if let transformer = self.transformer,
viewPortHandler.contentWidth > 10.0,
!viewPortHandler.isFullyZoomedOutY
{
// calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds)
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
min = inverted ? Double(p1.y) : Double(p2.y)
max = inverted ? Double(p2.y) : Double(p1.y)
}
computeAxisValues(min: min, max: max)
}
@objc open func computeAxisValues(min: Double, max: Double)
{
let yMin = min
let yMax = max
let labelCount = axis.labelCount
let range = abs(yMax - yMin)
guard
labelCount != 0,
range > 0,
range.isFinite
else
{
axis.entries = []
axis.centeredEntries = []
return
}
// Find out how much spacing (in y value space) between axis values
let rawInterval = range / Double(labelCount)
var interval = rawInterval.roundedToNextSignificant()
// If granularity is enabled, then do not allow the interval to go below specified granularity.
// This is used to avoid repeated values when rounding values for display.
if axis.granularityEnabled
{
interval = Swift.max(interval, axis.granularity)
}
// Normalize interval
let intervalMagnitude = pow(10.0, Double(Int(log10(interval)))).roundedToNextSignificant()
let intervalSigDigit = Int(interval / intervalMagnitude)
if intervalSigDigit > 5
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or 90
interval = floor(10.0 * Double(intervalMagnitude))
}
var n = axis.centerAxisLabelsEnabled ? 1 : 0
// force label count
if axis.isForceLabelsEnabled
{
interval = Double(range) / Double(labelCount - 1)
// Ensure stops contains at least n elements.
axis.entries.removeAll(keepingCapacity: true)
axis.entries.reserveCapacity(labelCount)
let values = stride(from: yMin, to: Double(labelCount) * interval + yMin, by: interval)
axis.entries.append(contentsOf: values)
n = labelCount
}
else
{
// no forced count
var first = interval == 0.0 ? 0.0 : ceil(yMin / interval) * interval
if axis.centerAxisLabelsEnabled
{
first -= interval
}
let last = interval == 0.0 ? 0.0 : (floor(yMax / interval) * interval).nextUp
if interval != 0.0, last != first
{
stride(from: first, through: last, by: interval).forEach { _ in n += 1 }
}
// Ensure stops contains at least n elements.
axis.entries.removeAll(keepingCapacity: true)
axis.entries.reserveCapacity(labelCount)
// Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0)
let values = stride(from: first, to: Double(n) * interval + first, by: interval).map { $0 == 0.0 ? 0.0 : $0 }
axis.entries.append(contentsOf: values)
}
// set decimals
if interval < 1
{
axis.decimals = Int(ceil(-log10(interval)))
}
else
{
axis.decimals = 0
}
if axis.centerAxisLabelsEnabled
{
axis.centeredEntries.reserveCapacity(n)
axis.centeredEntries.removeAll()
let offset: Double = interval / 2.0
axis.centeredEntries.append(contentsOf: axis.entries.map { $0 + offset })
}
}
}
|
ff29cf02735ba0afbd7409e7980c478d
| 31.416667 | 126 | 0.558179 | false | false | false | false |
agrippa1994/iOS-FH-Widget
|
refs/heads/master
|
EVReflection/pod/EVObject.swift
|
bsd-3-clause
|
2
|
//
// EVObject.swift
//
// Created by Edwin Vermeer on 5/2/15.
// Copyright (c) 2015 evict. All rights reserved.
//
import Foundation
/**
Object that will support NSCoding, Printable, Hashable and Equeatable for all properties. Use this object as your base class instead of NSObject and you wil automatically have support for all these protocols.
*/
public class EVObject: NSObject, NSCoding { // These are redundant in Swift 2+: CustomDebugStringConvertible, CustomStringConvertible, Hashable, Equatable
/**
This basic init override is needed so we can use EVObject as a base class.
*/
public required override init(){
super.init()
}
/**
Decode any object
This method is in EVObject and not in NSObject because you would get the error: Initializer requirement 'init(coder:)' can only be satisfied by a `required` initializer in the definition of non-final class 'NSObject'
:parameter: theObject The object that we want to decode.
:parameter: aDecoder The NSCoder that will be used for decoding the object.
*/
public convenience required init?(coder: NSCoder) {
self.init()
EVReflection.decodeObjectWithCoder(self, aDecoder: coder)
}
/**
Convenience init for creating an object whith the property values of a dictionary.
:parameter: dictionary The dictionary that will be used to create this object
*/
public required convenience init(dictionary:NSDictionary) {
self.init()
EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self)
}
/**
Convenience init for creating an object whith the contents of a json string.
:json: The json string that will be used to create this object
*/
public required convenience init(json:String?) {
self.init()
let jsonDict = EVReflection.dictionaryFromJson(json)
EVReflection.setPropertiesfromDictionary(jsonDict, anyObject: self)
}
/**
Encode this object using a NSCoder
:parameter: aCoder The NSCoder that will be used for encoding the object
*/
public func encodeWithCoder(aCoder: NSCoder) {
EVReflection.encodeWithCoder(self, aCoder: aCoder)
}
/**
Initialize this object from an archived file from the temp directory
:parameter: fileName The filename
*/
public convenience required init(fileNameInTemp:String) {
self.init()
let filePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(fileNameInTemp)
if let temp = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? NSObject {
EVReflection.setPropertiesfromDictionary( temp.toDictionary(false), anyObject: self)
}
}
/**
Initialize this object from an archived file from the documents directory
:parameter: fileName The filename
*/
public convenience required init(fileNameInDocuments:String) {
self.init()
let filePath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent(fileNameInDocuments)
if let temp = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? NSObject {
EVReflection.setPropertiesfromDictionary( temp.toDictionary(false), anyObject: self)
}
}
/**
Returns the pritty description of this object
:returns: The pritty description
*/
public override var description: String {
get {
return EVReflection.description(self)
}
}
/**
Returns the pritty description of this object
:returns: The pritty description
*/
public override var debugDescription: String {
get {
return EVReflection.description(self)
}
}
/**
Returns the hashvalue of this object
:returns: The hashvalue of this object
*/
public override var hashValue: Int {
get {
return Int(EVReflection.hashValue(self))
}
}
/**
Function for returning the hash for the NSObject based functionality
:returns: The hashvalue of this object
*/
public override var hash: Int {
get {
return self.hashValue
}
}
/**
Save this object to a file in the temp directory
:parameter: fileName The filename
:returns: Nothing
*/
public func saveToTemp(fileName:String) -> Bool {
let filePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(fileName)
return NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
}
#if os(tvOS)
// Save to documents folder is not supported on tvOS
#else
/**
Save this object to a file in the documents directory
:parameter: fileName The filename
:returns: Nothing
*/
public func saveToDocuments(fileName:String) -> Bool {
let filePath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent(fileName)
return NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
}
#endif
/**
Implementation of the NSObject isEqual comparisson method
This method is in EVObject and not in NSObject extension because you would get the error: method conflicts with previous declaration with the same Objective-C selector
:parameter: object The object where you want to compare with
:returns: Returns true if the object is the same otherwise false
*/
public override func isEqual(object: AnyObject?) -> Bool { // for isEqual:
if let dataObject = object as? EVObject {
return dataObject == self // just use our "==" function
}
return false
}
/**
Implementation of the setValue forUndefinedKey so that we can catch exceptions for when we use an optional Type like Int? in our object. Instead of using Int? you should use NSNumber?
This method is in EVObject and not in NSObject extension because you would get the error: method conflicts with previous declaration with the same Objective-C selector
:parameter: value The value that you wanted to set
:parameter: key The name of the property that you wanted to set
:returns: Nothing
*/
public override func setValue(value: AnyObject!, forUndefinedKey key: String) {
if let _ = self as? EVGenericsKVC {
NSLog("\nWARNING: Your class should have implemented the setValue forUndefinedKey. \n")
}
NSLog("\nWARNING: The class '\(EVReflection.swiftStringFromClass(self))' is not key value coding-compliant for the key '\(key)'\n There is no support for optional type, array of optionals or enum properties.\nAs a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information\n")
}
/**
Override this method when you want custom property mapping.
This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet
:returns: Return an array with valupairs of the object property name and json key name.
*/
public func propertyMapping() -> [(String?, String?)] {
return []
}
/**
Override this method when you want custom property value conversion
This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet
:returns: Returns an array where each item is a combination of the folowing 3 values: A string for the property name where the custom conversion is for, a setter function and a getter function.
*/
public func propertyConverters() -> [(String?, (Any?)->(), () -> Any? )] {
return []
}
/**
When a property is declared as a base type for multiple enherited classes, then this function will let you pick the right specific type based on the suplied dictionary.
- parameter dict: The dictionary for the specific type
- returns: The specific type
*/
public func getSpecificType(dict: NSDictionary) -> EVObject {
return self
}
}
|
f3187a4bc9441032ba52e1842ff80647
| 33.265306 | 344 | 0.675164 | false | false | false | false |
powerytg/Accented
|
refs/heads/master
|
Accented/UI/PearlFX/Filters/ColorFilterNode.swift
|
bsd-3-clause
|
2
|
//
// ColorFilterNode.swift
// PearlCam
//
// Created by Tiangong You on 6/10/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import GPUImage
class ColorFilterNode: FilterNode {
var rgbFilter = RGBAdjustment()
init() {
super.init(filter: rgbFilter)
enabled = true
}
var red : Float? {
didSet {
if red != nil {
rgbFilter.red = red!
}
}
}
var green : Float? {
didSet {
if green != nil {
rgbFilter.green = green!
}
}
}
var blue : Float? {
didSet {
if blue != nil {
rgbFilter.blue = blue!
}
}
}
override func cloneFilter() -> FilterNode? {
let clone = ColorFilterNode()
clone.enabled = enabled
clone.red = red
clone.green = green
clone.blue = blue
return clone
}
}
|
0ad0d7af18bfd56c1619993f06033306
| 17.566038 | 55 | 0.479675 | false | false | false | false |
piscoTech/GymTracker
|
refs/heads/master
|
Gym Tracker Core/GTCircuit.swift
|
mit
|
1
|
//
// GTCircuit.swift
// Gym Tracker
//
// Created by Marco Boschi on 13/08/2018.
// Copyright © 2018 Marco Boschi. All rights reserved.
//
//
import Foundation
import CoreData
@objc(GTCircuit)
final public class GTCircuit: GTExercise, ExerciseCollection {
override class var objectType: String {
return "GTCircuit"
}
public static let collectionType = GTLocalizedString("CIRCUIT", comment: "Circuit")
@NSManaged public private(set) var exercises: Set<GTSetsExercise>
override class func loadWithID(_ id: String, fromDataManager dataManager: DataManager) -> GTCircuit? {
let req = NSFetchRequest<GTCircuit>(entityName: self.objectType)
let pred = NSPredicate(format: "id == %@", id)
req.predicate = pred
return dataManager.executeFetchRequest(req)?.first
}
public override var title: String {
return Self.collectionType
}
public override var summary: String {
return exerciseList.lazy.map { $0.title }.joined(separator: ", ")
}
override public var isValid: Bool {
return workout != nil && isSubtreeValid
}
override var isSubtreeValid: Bool {
return exercises.count > 1 && exercises.reduce(true) { $0 && $1.isValid } && exercisesError.isEmpty
}
public override var isPurgeableToValid: Bool {
return false
}
public override var shouldBePurged: Bool {
return exercises.isEmpty
}
override public var parentLevel: CompositeWorkoutLevel? {
return workout
}
override public var subtreeNodes: Set<GTDataObject> {
return Set(exercises.flatMap { $0.subtreeNodes } + [self])
}
public override func purge(onlySettings: Bool) -> [GTDataObject] {
return exercises.reduce([]) { $0 + $1.purge(onlySettings: onlySettings) }
}
public override func removePurgeable() -> [GTDataObject] {
var res = [GTDataObject]()
for e in exercises {
if e.shouldBePurged {
res.append(e)
self.remove(part: e)
} else {
res.append(contentsOf: e.removePurgeable())
}
}
recalculatePartsOrder()
return res
}
/// Whether or not the exercises of this circuit are valid inside of it.
///
/// An exercise has its index in `exerciseList` included if it has not the same number of sets as the most frequent sets count in the circuit.
public var exercisesError: [Int] {
return GTCircuit.invalidIndices(for: exerciseList.map { $0.setsCount })
}
class func invalidIndices(for setsCount: [Int?], mode m: Int?? = nil) -> [Int] {
let mode = m ?? setsCount.mode
return zip(setsCount, 0 ..< setsCount.count).filter { $0.0 == nil || $0.0 != mode }.map { $0.1 }
}
// MARK: - Exercises handling
public var exerciseList: [GTSetsExercise] {
return Array(exercises).sorted { $0.order < $1.order }
}
public func add(parts: GTSetsExercise...) {
for se in parts {
se.order = Int32(self.exercises.count)
se.set(circuit: self)
}
}
public func remove(part se: GTSetsExercise) {
exercises.remove(se)
recalculatePartsOrder()
}
}
|
2c4ad276f1a0d565bddeda6c48bf96da
| 24.964602 | 143 | 0.697682 | false | false | false | false |
vimeo/VimeoNetworking
|
refs/heads/develop
|
Tests/Shared/AlbumTests.swift
|
mit
|
1
|
//
// AlbumTests.swift
// VimeoNetworkingExample-iOS
//
// Created by Hawkins, Jason on 10/26/18.
// Copyright © 2018 Vimeo. All rights reserved.
//
import XCTest
@testable import VimeoNetworking
class AlbumTests: XCTestCase {
private var testAlbum: Album?
private var albumJSONDictionary: VimeoClient.ResponseDictionary?
override func setUp() {
guard let albumJSONDictionary = ResponseUtilities.loadResponse(from: "album-response.json") else {
return
}
self.albumJSONDictionary = albumJSONDictionary
self.testAlbum = try! VIMObjectMapper.mapObject(responseDictionary: albumJSONDictionary) as Album
}
override func tearDown() {
self.testAlbum = nil
self.albumJSONDictionary = nil
}
func test_AlbumObject_ParsesCorrectly() {
guard let album = self.testAlbum else {
assertionFailure("Failed to unwrap the test album.")
return
}
XCTAssertEqual(album.albumName, "2018")
XCTAssertEqual(album.albumDescription, "Favorites from 2018.")
XCTAssertEqual(album.albumLogo?.uri, "/users/267176/albums/5451829/logos/18363")
XCTAssertEqual(album.privacy?.view, "anybody")
XCTAssertEqual(album.duration, 1003)
XCTAssertEqual(album.uri, "/users/267176/albums/5451829")
XCTAssertEqual(album.link, "https://vimeo.com/album/5451829")
XCTAssertNotNil(album.embed?.html)
XCTAssertNotNil(album.videoThumbnails)
XCTAssertNotNil(album.user)
XCTAssertEqual(album.theme, "dark")
}
func test_AlbumPictures_ParsesCorrectly() {
guard let album = self.testAlbum else {
assertionFailure("Failed to unwrap the test album.")
return
}
XCTAssertNotNil(album.videoThumbnails)
XCTAssertTrue(album.videoThumbnails?.count == 2)
let videoThumbnails0 = album.videoThumbnails![0] as! VIMPictureCollection
let videoThumbnails1 = album.videoThumbnails![1] as! VIMPictureCollection
XCTAssertEqual(videoThumbnails0.uri, "/videos/248249215/pictures/673727920")
XCTAssertEqual(videoThumbnails1.uri, "/videos/190063150/pictures/624750928")
}
func test_AlbumDates_ParsesAndFormatCorrectly() {
guard let album = self.testAlbum else {
assertionFailure("Failed to unwrap the test album.")
return
}
XCTAssertNotNil(album.createdTimeString)
XCTAssertEqual(album.createdTime!.timeIntervalSince1970, TimeInterval(1538405413))
XCTAssertNotNil(album.modifiedTimeString)
XCTAssertEqual(album.modifiedTime!.timeIntervalSince1970, TimeInterval(1540585280))
}
func test_AlbumLogoOjbect_ParsesCorrectly() {
guard let album = self.testAlbum else {
assertionFailure("Failed to unwrap the test album.")
return
}
guard let logo = album.albumLogo?.pictures?.first as? VIMPicture else {
assertionFailure("Failed to unwrap the test album's logo.")
return
}
XCTAssertEqual(logo.width, 200)
XCTAssertEqual(logo.height, 200)
XCTAssertEqual(logo.link, "https://i.vimeocdn.com/album_custom_logo/18363_200x200")
}
func test_AlbumEmbedObject_ParsesCorrectly() {
guard let album = self.testAlbum else {
assertionFailure("Failed to unwrap the test album.")
return
}
XCTAssertNotNil(album.embed)
XCTAssertEqual(album.embed?.html,
"""
<div style='padding:56.25% 0 0 0;position:relative;'><iframe src='https://vimeo.com/album/5451829/embed' allowfullscreen frameborder='0' style='position:absolute;top:0;left:0;width:100%;height:100%;'></iframe></div>
""")
}
func test_AlbumConnection_ParsesCorrectly() {
guard let album = self.testAlbum else {
assertionFailure("Failed to unwrap the test album.")
return
}
XCTAssertNotNil(album.connection(named: VIMConnectionNameVideos), "Expected to find a videos connection but return nil instead.")
let videosConnection = album.connection(named: VIMConnectionNameVideos)
XCTAssertEqual(videosConnection?.uri, "/albums/5451829/videos", "The connection URI's do not match.")
XCTAssertEqual(videosConnection?.total, 2, "The total number of videos in the connection do not much the expected number of 2.")
}
func test_isPasswordProtected_returnsTrue_whenPrivacyViewIsPassword() {
let privacyDictionary: [String: Any] = ["view": "password"]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let albumDictionary: [String: Any] = ["privacy": privacy as Any]
let testAlbum = Album(keyValueDictionary: albumDictionary)!
XCTAssertTrue(testAlbum.isPasswordProtected(), "Test album should return as password protected.")
}
func test_privacyPassword_isEqualToExpectedValue_whenPrivacyViewIsPassword() {
let privacyDictionary: [String: Any] = ["view": "password", "password": "test"]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let albumDictionary: [String: Any] = ["privacy": privacy as Any]
let testAlbum = Album(keyValueDictionary: albumDictionary)!
XCTAssertTrue(testAlbum.isPasswordProtected(), "Test album should return as password protected.")
XCTAssertEqual(testAlbum.privacy?.password, "test", "Password should be 'test'.")
}
func test_isPasswordProtected_returnsFalse_whenPrivacyViewIsEmbedOnly() {
let privacyDictionary: [String: Any] = ["view": "embed_only"]
let privacy = VIMPrivacy(keyValueDictionary: privacyDictionary)!
let videoDictionary: [String: Any] = ["privacy": privacy as Any]
let testAlbum = Album(keyValueDictionary: videoDictionary)!
XCTAssertFalse(testAlbum.isPasswordProtected(), "Test album should not return as password protected.")
}
}
|
599047c921ff18d5ed16e03b25e89eca
| 42.091549 | 227 | 0.670534 | false | true | false | false |
brave/browser-ios
|
refs/heads/development
|
Client/Frontend/Browser/TabTrayController.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
import CoreData
struct TabTrayControllerUX {
static let CornerRadius = BraveUX.TabTrayCellCornerRadius
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1)
static let TitleBoxHeight = CGFloat(32.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonMargin = CGFloat(4.0)
static let CloseButtonEdgeInset = CGFloat(6)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
}
struct LightTabCellUX {
static let TabTitleTextColor = BraveUX.GreyJ
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.white
}
protocol TabCellDelegate: class {
func tabCellDidClose(_ cell: TabCell)
}
class TabCell: UICollectionViewCell {
static let Identifier = "TabCellIdentifier"
let shadowView = UIView()
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleLbl: UILabel
let favicon: UIImageView = UIImageView()
let titleWrapperBackground = UIView()
let closeButton: UIButton
let placeholderFavicon: UIImageView = UIImageView()
var titleWrapper: UIView = UIView()
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
shadowView.layer.cornerRadius = TabTrayControllerUX.CornerRadius
shadowView.layer.masksToBounds = false
backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
backgroundHolder.layer.borderWidth = 0
backgroundHolder.layer.masksToBounds = true
background.contentMode = UIViewContentMode.scaleAspectFill
background.isUserInteractionEnabled = false
background.layer.masksToBounds = true
background.alignLeft = true
background.alignTop = true
favicon.layer.cornerRadius = 2.0
favicon.layer.masksToBounds = true
titleLbl = UILabel()
titleLbl.backgroundColor = .clear
titleLbl.textAlignment = NSTextAlignment.left
titleLbl.isUserInteractionEnabled = false
titleLbl.numberOfLines = 1
titleLbl.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
closeButton = UIButton()
closeButton.setImage(UIImage(named: "close"), for: .normal)
closeButton.tintColor = BraveUX.GreyG
titleWrapperBackground.backgroundColor = UIColor.white
titleWrapper.backgroundColor = .clear
titleWrapper.addSubview(titleWrapperBackground)
titleWrapper.addSubview(closeButton)
titleWrapper.addSubview(titleLbl)
titleWrapper.addSubview(favicon)
super.init(frame: frame)
closeButton.addTarget(self, action: #selector(TabCell.SELclose), for: UIControlEvents.touchUpInside)
contentView.clipsToBounds = false
clipsToBounds = false
animator = SwipeAnimator(animatingView: shadowView, container: self)
shadowView.addSubview(backgroundHolder)
backgroundHolder.addSubview(background)
backgroundHolder.addSubview(titleWrapper)
contentView.addSubview(shadowView)
placeholderFavicon.layer.cornerRadius = 8.0
placeholderFavicon.layer.masksToBounds = true
backgroundHolder.addSubview(placeholderFavicon)
setupConstraints()
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: Strings.Close, target: animator, selector: #selector(SELclose))
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupConstraints() {
let generalOffset = 4
shadowView.snp.remakeConstraints { make in
make.edges.equalTo(shadowView.superview!)
}
backgroundHolder.snp.remakeConstraints { make in
make.edges.equalTo(backgroundHolder.superview!)
}
background.snp.remakeConstraints { make in
make.edges.equalTo(background.superview!)
}
placeholderFavicon.snp.remakeConstraints { make in
make.size.equalTo(CGSize(width: 60, height: 60))
make.center.equalTo(placeholderFavicon.superview!)
}
favicon.snp.remakeConstraints { make in
make.top.left.equalTo(favicon.superview!).offset(generalOffset)
make.size.equalTo(titleWrapper.snp.height).offset(-generalOffset * 2)
}
titleWrapper.snp.remakeConstraints { make in
make.left.top.equalTo(titleWrapper.superview!)
make.width.equalTo(titleWrapper.superview!.snp.width)
make.height.equalTo(TabTrayControllerUX.TitleBoxHeight)
}
titleWrapperBackground.snp.remakeConstraints { make in
make.top.left.right.equalTo(titleWrapperBackground.superview!)
make.height.equalTo(TabTrayControllerUX.TitleBoxHeight + 15)
}
titleLbl.snp.remakeConstraints { make in
make.left.equalTo(favicon.snp.right).offset(generalOffset)
make.right.equalTo(closeButton.snp.left).offset(generalOffset)
make.top.bottom.equalTo(titleLbl.superview!)
}
closeButton.snp.remakeConstraints { make in
make.size.equalTo(titleWrapper.snp.height)
make.centerY.equalTo(titleWrapper)
make.right.equalTo(closeButton.superview!)
}
}
override func layoutSubviews() {
super.layoutSubviews()
// Frames do not seem to update until next runloop cycle
DispatchQueue.main.async {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.titleWrapperBackground.bounds
gradientLayer.colors = [UIColor(white: 1.0, alpha: 0.98).cgColor, UIColor(white: 1.0, alpha: 0.9).cgColor, UIColor.clear.cgColor]
self.titleWrapperBackground.layer.mask = gradientLayer
}
}
override func prepareForReuse() {
// TODO: Move more of this to cellForItem
// Reset any close animations.
backgroundHolder.layer.borderColor = UIColor(white: 0.0, alpha: 0.15).cgColor
backgroundHolder.layer.borderWidth = 1
shadowView.alpha = 1
shadowView.transform = CGAffineTransform.identity
shadowView.layer.shadowOpacity = 0
background.image = nil
placeholderFavicon.isHidden = true
placeholderFavicon.image = nil
favicon.image = nil
titleLbl.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
}
override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
animator.close(direction == .right)
return true
}
@objc
func SELclose() {
self.animator.SELcloseWithoutGesture()
}
}
struct PrivateModeStrings {
static let toggleAccessibilityLabel = Strings.Private_Mode
static let toggleAccessibilityHint = Strings.Turns_private_mode_on_or_off
static let toggleAccessibilityValueOn = Strings.On
static let toggleAccessibilityValueOff = Strings.Off
}
protocol TabTrayDelegate: class {
func tabTrayDidDismiss(_ tabTray: TabTrayController)
func tabTrayDidAddBookmark(_ tab: Browser)
func tabTrayDidAddToReadingList(_ tab: Browser) -> ReadingListClientRecord?
func tabTrayRequestsPresentationOf(_ viewController: UIViewController)
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
var collectionView: UICollectionView!
lazy var addTabButton: UIButton = {
let addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add")?.withRenderingMode(.alwaysTemplate), for: .normal)
addTabButton.addTarget(self, action: #selector(TabTrayController.SELdidClickAddTab), for: .touchUpInside)
addTabButton.accessibilityLabel = Strings.Add_Tab
addTabButton.accessibilityIdentifier = "TabTrayController.addTabButton"
return addTabButton
}()
var collectionViewTransitionSnapshot: UIView?
/// Views to be animationed when preseting the Tab Tray.
/// There is some bug related to the blurring background the tray controller attempts to handle.
/// On animating self.view the blur effect will not animate (just pops in at the animation end),
/// and must be animated manually. Instead of animating the larger view elements, smaller pieces
/// must be animated in order to achieve a blur-incoming animation
var viewsToAnimate: [UIView] = []
fileprivate(set) internal var privateMode: Bool = false {
didSet {
if privateMode {
togglePrivateMode.isSelected = true
togglePrivateMode.accessibilityValue = PrivateModeStrings.toggleAccessibilityValueOn
togglePrivateMode.backgroundColor = .white
addTabButton.tintColor = UIColor.white
blurBackdropView.effect = UIBlurEffect(style: .dark)
} else {
togglePrivateMode.isSelected = false
togglePrivateMode.accessibilityValue = PrivateModeStrings.toggleAccessibilityValueOff
togglePrivateMode.backgroundColor = .clear
addTabButton.tintColor = BraveUX.GreyI
blurBackdropView.effect = UIBlurEffect(style: .light)
}
tabDataSource.updateData()
collectionView?.reloadData()
}
}
fileprivate var tabsToDisplay: [Browser] {
return tabManager.tabs.displayedTabsForCurrentPrivateMode
}
lazy var togglePrivateMode: UIButton = {
let button = UIButton()
button.setTitle(Strings.Private, for: .normal)
button.setTitleColor(BraveUX.GreyI, for: .normal)
button.titleLabel!.font = UIFont.systemFont(ofSize: button.titleLabel!.font.pointSize + 1, weight: UIFont.Weight.medium)
button.contentEdgeInsets = UIEdgeInsetsMake(0, 4 /* left */, 0, 4 /* right */)
button.layer.cornerRadius = 4.0
button.addTarget(self, action: #selector(TabTrayController.SELdidTogglePrivateMode), for: .touchUpInside)
button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel
button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint
button.accessibilityIdentifier = "TabTrayController.togglePrivateMode"
return button
}()
lazy var doneButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.Done, for: .normal)
button.setTitleColor(BraveUX.GreyI, for: .normal)
button.titleLabel!.font = UIFont.systemFont(ofSize: button.titleLabel!.font.pointSize + 1, weight: UIFont.Weight.regular)
button.contentEdgeInsets = UIEdgeInsetsMake(0, 4 /* left */, 0, 4 /* right */)
button.layer.cornerRadius = 4.0
button.addTarget(self, action: #selector(TabTrayController.SELdidTapDoneButton), for: .touchUpInside)
button.accessibilityIdentifier = "TabTrayController.doneButton"
return button
}()
fileprivate var blurBackdropView = UIVisualEffectView()
fileprivate lazy var emptyPrivateTabsView: UIView = {
return self.newEmptyPrivateTabsView()
}()
fileprivate lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(cellDelegate: self)
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
override func dismiss(animated flag: Bool, completion: (() -> Void)?) {
super.dismiss(animated: flag, completion:completion)
UIView.animate(withDuration: 0.2, animations: {
getApp().browserViewController.toolbar?.leavingTabTrayMode()
})
getApp().browserViewController.updateTabCountUsingTabManager(getApp().tabManager)
}
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
tabManager.addDelegate(self)
}
convenience init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate) {
self.init(tabManager: tabManager, profile: profile)
self.delegate = tabTrayDelegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
self.tabManager.removeDelegate(self)
}
@objc func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
self.collectionView.reloadData()
}
@objc func onTappedBackground(_ gesture: UITapGestureRecognizer) {
dismiss(animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
// TODO: centralize timing
UIView.animate(withDuration: 0.2, animations: {
self.viewsToAnimate.forEach { $0.alpha = 1.0 }
})
let tabs = WeakList<Browser>()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabs.insert($0)
}
guard let selectedTab = tabManager.selectedTab else { return }
let selectedIndex = tabs.index(of: selectedTab) ?? 0
self.collectionView.scrollToItem(at: IndexPath(item: selectedIndex, section: 0), at: UICollectionViewScrollPosition.centeredVertically, animated: false)
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = Strings.Tabs_Tray
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = UIColor.clear
// Background view created for tapping background closure
collectionView.backgroundView = UIView()
collectionView.backgroundView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(TabTrayController.onTappedBackground(_:))))
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
longPressGesture.minimumPressDuration = 0.2
collectionView.addGestureRecognizer(longPressGesture)
viewsToAnimate = [blurBackdropView, collectionView, addTabButton, togglePrivateMode, doneButton]
viewsToAnimate.forEach {
$0.alpha = 0.0
view.addSubview($0)
}
makeConstraints()
if profile.prefs.boolForKey(kPrefKeyPrivateBrowsingAlwaysOn) ?? false {
togglePrivateMode.isHidden = true
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.alpha = privateTabsAreEmpty() ? 1 : 0
emptyPrivateTabsView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
// Make sure buttons are all setup before this, to allow
// privateMode setter to setup final visuals
let selectedTabIsPrivate = tabManager.selectedTab?.isPrivate ?? false
privateMode = PrivateBrowsing.singleton.isOn || selectedTabIsPrivate
doneButton.setTitleColor(privateMode ? BraveUX.GreyG : BraveUX.GreyG, for: .normal)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
@objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// Used to update the glow effect on the selected tab
// and update screenshot framing/positioning
// Must be scheduled on next runloop
DispatchQueue.main.async {
self.collectionView.reloadData()
}
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
fileprivate func makeConstraints() {
if UIDevice.current.userInterfaceIdiom == .phone {
doneButton.snp.makeConstraints { make in
if #available(iOS 11.0, *) {
make.right.equalTo(self.view.safeAreaLayoutGuide.snp.right).offset(-30)
} else {
make.right.equalTo(self.view).offset(-30)
}
make.centerY.equalTo(self.addTabButton.snp.centerY)
}
togglePrivateMode.snp.makeConstraints { make in
if #available(iOS 11.0, *) {
make.left.equalTo(self.view.safeAreaLayoutGuide.snp.left).offset(30)
} else {
make.left.equalTo(30)
}
make.centerY.equalTo(self.addTabButton.snp.centerY)
}
addTabButton.snp.makeConstraints { make in
if #available(iOS 11.0, *) {
make.bottom.equalTo(self.view).inset(getApp().window?.safeAreaInsets.bottom ?? 0)
} else {
make.bottom.equalTo(self.view)
}
make.centerX.equalTo(self.view)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp.makeConstraints { make in
make.bottom.equalTo(addTabButton.snp.top)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
if #available(iOS 11.0, *) {
make.left.equalTo(self.view.safeAreaLayoutGuide.snp.left)
make.right.equalTo(self.view.safeAreaLayoutGuide.snp.right)
} else {
make.left.right.equalTo(self.view)
}
}
blurBackdropView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
}
else {
doneButton.isHidden = true
togglePrivateMode.snp.makeConstraints { make in
make.right.equalTo(addTabButton.snp.left).offset(-10)
make.centerY.equalTo(self.addTabButton.snp.centerY)
}
addTabButton.snp.makeConstraints { make in
make.trailing.equalTo(self.view)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(addTabButton.snp.bottom)
make.left.right.bottom.equalTo(self.view)
}
blurBackdropView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
}
}
// View we display when there are no private tabs created
fileprivate func newEmptyPrivateTabsView() -> UIView {
let emptyView = UIView()
emptyView.backgroundColor = BraveUX.GreyI
return emptyView
}
// MARK: Selectors
@objc func SELdidTapDoneButton() {
self.dismiss(animated: true, completion: nil)
}
@objc func SELdidClickAddTab() {
openNewTab()
}
@objc func SELdidTogglePrivateMode() {
let fromView: UIView
if privateTabsAreEmpty() {
fromView = emptyPrivateTabsView
} else {
let snapshot = collectionView.snapshotView(afterScreenUpdates: false)
snapshot!.frame = collectionView.frame
view.insertSubview(snapshot!, aboveSubview: collectionView)
fromView = snapshot!
}
privateMode = !privateMode
doneButton.setTitleColor(privateMode ? BraveUX.GreyG : BraveUX.GreyG, for: .normal)
if privateMode {
PrivateBrowsing.singleton.enter()
} else {
view.isUserInteractionEnabled = false
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView.center = view.center
activityView.startAnimating()
self.view.addSubview(activityView)
PrivateBrowsing.singleton.exit().uponQueue(DispatchQueue.main) {
self.view.isUserInteractionEnabled = true
activityView.stopAnimating()
}
}
tabDataSource.updateData()
collectionView.layoutSubviews()
let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
// This needs to be unwrapped due to minor swift differences between 4.1 and 4.2
guard let collectionView = collectionView else { return }
let toView = privateTabsAreEmpty() ? emptyPrivateTabsView : collectionView
toView.transform = scaleDownTransform
toView.alpha = 0
UIView.animate(withDuration: 0.4, delay: 0, options: [], animations: { () -> Void in
fromView.alpha = 0
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) { finished in
if fromView != self.emptyPrivateTabsView {
fromView.removeFromSuperview()
}
if self.privateMode {
self.openNewTab()
}
}
}
fileprivate func privateTabsAreEmpty() -> Bool {
return privateMode && tabManager.tabs.privateTabs.count == 0
}
func changePrivacyMode(_ isPrivate: Bool) {
if isPrivate != privateMode {
guard let _ = collectionView else {
privateMode = isPrivate
return
}
SELdidTogglePrivateMode()
}
}
fileprivate func openNewTab(_ request: URLRequest? = nil) {
if privateMode {
emptyPrivateTabsView.isHidden = true
}
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({
// TODO: This logic seems kind of finicky
var tab: Browser?
let id = TabMO.create().syncUUID
tab = self.tabManager.addTab(request, id: id)
tab?.tabID = id
if let tab = tab {
self.tabManager.selectTab(tab)
}
})
}
}
// MARK: - App Notifications
extension TabTrayController {
@objc func SELappWillResignActiveNotification() {
if privateMode {
collectionView.alpha = 0
}
}
@objc func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.collectionView.alpha = 1
},
completion: nil)
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
self.dismiss(animated: true, completion: nil)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Browser?) {
}
func tabManager(_ tabManager: TabManager, didCreateWebView tab: Browser, url: URL?, at: Int?) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Browser) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.index(of: tab) else { return }
tabDataSource.updateData()
self.collectionView?.performBatchUpdates({
self.collectionView.insertItems(at: [IndexPath(item: index, section: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.dismiss(animated: true, completion: nil)
}
}
})
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Browser) {
var removedIndex = -1
for i in 0..<tabDataSource.tabList.count() {
let tabRef = tabDataSource.tabList.at(i)
if tabRef == nil || getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.index(of: tabRef!) == nil {
removedIndex = i
break
}
}
tabDataSource.updateData()
if (removedIndex < 0) {
return
}
self.collectionView.deleteItems(at: [IndexPath(item: removedIndex, section: 0)])
if privateTabsAreEmpty() {
emptyPrivateTabsView.alpha = 1
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells as! [TabCell]
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in
return a.section < b.section || (a.section == b.section && a.row < b.row)
}
if indexPaths.count == 0 {
return Strings.No_tabs
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 0)
if (firstTab == lastTab) {
let format = Strings.Tab_xofx_template
return String(format: format, NSNumber(value: firstTab), NSNumber(value: tabCount))
} else {
let format = Strings.Tabs_xtoxofx_template
return String(format: format, NSNumber(value: firstTab), NSNumber(value: lastTab), NSNumber(value: tabCount))
}
}
}
fileprivate func removeTabUtil(_ tabManager: TabManager, tab: Browser) {
let isAlwaysPrivate = getApp().profile?.prefs.boolForKey(kPrefKeyPrivateBrowsingAlwaysOn) ?? false
let createIfNone = true
tabManager.removeTab(tab, createTabIfNoneLeft: createIfNone)
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPath(for: tabCell) {
let tab = tabsToDisplay[indexPath.item]
removeTabUtil(tabManager, tab: tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.Closing_tab)
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
let indexPath = collectionView.indexPath(for: cell)!
let tab = tabsToDisplay[indexPath.item]
removeTabUtil(tabManager, tab: tab)
}
}
extension TabTrayController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
let request = URLRequest(url: url)
openNewTab(request)
}
}
fileprivate class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: TabCellDelegate & SwipeAnimatorDelegate
fileprivate var tabList = WeakList<Browser>()
init(cellDelegate: TabCellDelegate & SwipeAnimatorDelegate) {
self.cellDelegate = cellDelegate
super.init()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabList.insert($0)
}
}
func updateData() {
tabList = WeakList<Browser>()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabList.insert($0)
}
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TabCell.Identifier, for: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
guard let tab = tabList.at(indexPath.item) else {
assert(false)
return tabCell
}
let title = tab.displayTitle
tabCell.titleLbl.text = title
if !title.isEmpty {
tabCell.accessibilityLabel = title
} else {
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = Strings.Swipe_right_or_left_with_three_fingers_to_close_the_tab
tabCell.favicon.backgroundColor = BraveUX.TabTrayCellBackgroundColor
tab.screenshot(callback: { (image) in
tabCell.background.image = image
})
tabCell.placeholderFavicon.isHidden = tab.isScreenshotSet
if tab.isHomePanel {
tabCell.favicon.isHidden = true
} else {
// Fetching favicon
if let tabMO = TabMO.get(fromId: tab.tabID, context: DataController.newBackgroundContext()), let urlString = tabMO.url, let url = URL(string: urlString) {
weak var weakSelf = self
if ImageCache.shared.hasImage(url, type: .square) {
// no relationship - check cache for icon which may have been stored recently for url.
ImageCache.shared.image(url, type: .square, callback: { (image) in
postAsyncToMain {
tabCell.favicon.image = image
tabCell.placeholderFavicon.image = image
}
})
}
else {
// no relationship - attempt to resolove domain problem
let context = DataController.viewContext
if let domain = Domain.getOrCreateForUrl(url, context: context), let faviconMO = domain.favicon, let urlString = faviconMO.url, let faviconurl = URL(string: urlString) {
postAsyncToMain {
weakSelf?.setCellImage(tabCell, iconUrl: faviconurl, cacheWithUrl: url)
}
}
else {
// last resort - download the icon
downloadFaviconsAndUpdateForUrl(url, collectionView: collectionView, indexPath: indexPath)
}
}
}
}
// TODO: Move most view logic here instead of `init` or `prepareForReuse`
// If the current tab add heightlighting
if getApp().tabManager.selectedTab == tab {
tabCell.backgroundHolder.layer.borderColor = BraveUX.LightBlue.withAlphaComponent(0.75).cgColor
tabCell.backgroundHolder.layer.borderWidth = 1
tabCell.shadowView.layer.shadowRadius = 5
tabCell.shadowView.layer.shadowColor = BraveUX.LightBlue.cgColor
tabCell.shadowView.layer.shadowOpacity = 1.0
tabCell.shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
tabCell.shadowView.layer.shadowPath = UIBezierPath(roundedRect: tabCell.bounds, cornerRadius: tabCell.backgroundHolder.layer.cornerRadius).cgPath
tabCell.background.alpha = 1.0
} else {
tabCell.backgroundHolder.layer.borderWidth = 0
tabCell.shadowView.layer.shadowRadius = 2
tabCell.shadowView.layer.shadowColor = UIColor(white: 0.0, alpha: 0.15).cgColor
tabCell.shadowView.layer.shadowOpacity = 1.0
tabCell.shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
tabCell.shadowView.layer.shadowPath = UIBezierPath(roundedRect: tabCell.bounds, cornerRadius: tabCell.backgroundHolder.layer.cornerRadius).cgPath
tabCell.background.alpha = 0.7
}
return tabCell
}
fileprivate func downloadFaviconsAndUpdateForUrl(_ url: URL, collectionView: UICollectionView, indexPath: IndexPath) {
weak var weakSelf = self
FaviconFetcher.getForURL(url).uponQueue(DispatchQueue.main) { result in
guard let favicons = result.successValue, favicons.count > 0, let foundIconUrl = favicons.first?.url.asURL, let cell = collectionView.cellForItem(at: indexPath) as? TabCell else { return }
weakSelf?.setCellImage(cell, iconUrl: foundIconUrl, cacheWithUrl: url)
}
}
fileprivate func setCellImage(_ cell: TabCell, iconUrl: URL, cacheWithUrl: URL) {
ImageCache.shared.image(cacheWithUrl, type: .square, callback: { (image) in
if image != nil {
postAsyncToMain {
cell.placeholderFavicon.image = image
cell.favicon.image = image
}
}
else {
postAsyncToMain {
cell.favicon.setFaviconImage(with: iconUrl, cacheUrl: cacheWithUrl)
}
}
})
}
// fileprivate func getImageColor(image: UIImage) -> UIColor? {
// let rgba = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
// let colorSpace = CGColorSpaceCreateDeviceRGB()
// let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
// let context: CGContext = CGContext(data: rgba, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: info.rawValue)!
//
// guard let newImage = image.cgImage else { return nil }
// context.draw(newImage, in: CGRect(x: 0, y: 0, width: 1, height: 1))
//
// // Has issues, often sets background to black. experimenting without box for now.
// let red = CGFloat(rgba[0]) / 255.0
// let green = CGFloat(rgba[1]) / 255.0
// let blue = CGFloat(rgba[2]) / 255.0
// let colorFill: UIColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
//
// return colorFill
// }
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabList.count()
}
@objc func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
@objc func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let tab = tabList.at(sourceIndexPath.row) else { return }
// Find original from/to index... we need to target the full list not partial.
guard let tabManager = getApp().tabManager else { return }
guard let from = tabManager.tabs.tabs.index(where: {$0 === tab}) else { return }
let toTab = tabList.at(destinationIndexPath.row)
guard let to = tabManager.tabs.tabs.index(where: {$0 === toTab}) else { return }
tabManager.move(tab: tab, from: from, to: to)
updateData()
NotificationCenter.default.post(name: kRearangeTabNotification, object: nil)
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(_ index :Int)
}
fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
fileprivate var traitCollection: UITraitCollection
fileprivate var profile: Profile
fileprivate var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = TabTrayControllerUX.TitleBoxHeight * (compactLayout ? 7 : 6)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact {
return rint(UIScreen.main.bounds.height / 3)
} else {
return TabTrayControllerUX.TitleBoxHeight * 8
}
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns))
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
fileprivate class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
fileprivate override var collectionViewContentSize : CGSize {
var calculatedSize = super.collectionViewContentSize
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.white
static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.medium)
static let DescriptionColor = UIColor.white
static let DescriptionFont = UIFont.systemFont(ofSize: 17)
static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
static let TextMargin: CGFloat = 18
static let LearnMoreMargin: CGFloat = 30
static let MaxDescriptionWidth: CGFloat = 250
}
|
e50cb4326b7df4aed6c5c34002bd2024
| 40.050514 | 200 | 0.660324 | false | false | false | false |
kellanburket/franz
|
refs/heads/master
|
Sources/Franz/Group.swift
|
mit
|
1
|
//
// Group.swift
// Pods
//
// Created by Kellan Cummings on 1/26/16.
//
//
import Foundation
/**
Base class for all Client Groups.
*/
class Group {
fileprivate var _broker: Broker
fileprivate var _clientId: String
fileprivate var _groupProtocol: GroupProtocol
fileprivate var _groupId: String
fileprivate var _generationId: Int32
fileprivate var _version: ApiVersion = 0
private var _state: GroupState?
/**
Group Protocol
*/
var groupProtocol: String {
return _groupProtocol.value
}
/**
Generation Id
*/
var generationId: Int32 {
return _generationId
}
/**
Group Id
*/
var id: String {
return _groupId
}
internal init(
broker: Broker,
clientId: String,
groupProtocol: GroupProtocol,
groupId: String,
generationId: Int32
) {
_broker = broker
_clientId = clientId
_groupProtocol = groupProtocol
_groupId = groupId
_generationId = generationId
}
/**
Retreive the state of the current group.
- Parameter callback: a closure which takes a group id and a state of that group as its parameters
*/
func getState(_ callback: @escaping (String, GroupState) -> ()) {
_broker.describeGroups(self.id, clientId: _clientId) { id, state in
self._state = state
callback(id, state)
}
}
var topics = Set<TopicName>()
internal(set) var assignedPartitions = [TopicName: [PartitionId]]()
}
/**
A Consumer Group
*/
class ConsumerGroup: Group {
internal init(
broker: Broker,
clientId: String,
groupId: String,
generationId: Int32
) {
super.init(
broker: broker,
clientId: clientId,
groupProtocol: GroupProtocol.consumer,
groupId: groupId,
generationId: generationId
)
}
}
/**
An abstraction of a Broker's relationship to a group.
*/
class GroupMembership {
var _group: Group
var _memberId: String
let members: [Member]
/**
A Group
*/
var group: Group {
return _group
}
/**
The Broker's id
*/
var memberId: String {
return _memberId
}
init(group: Group, memberId: String, members: [Member]) {
self._group = group
self._memberId = memberId
self.members = members
}
/**
Sync the broker with the Group Coordinator
*/
func sync(
_ topics: [TopicName: [PartitionId]],
data: Data = Data(),
callback: (() -> ())? = nil
) {
group._broker.syncGroup(
group.id,
generationId: group.generationId,
memberId: memberId,
topics: topics,
userData: data,
version: group._version) { membership in
for assignment in membership.partitionAssignment {
self.group.assignedPartitions[assignment.topic] = assignment.partitions.map { $0 }
}
self.group.topics = Set(membership.partitionAssignment.map { $0.topic })
callback?()
}
}
/**
Leave the group
- Parameter callback: called when the group has successfully been left
*/
func leave(_ callback: (() -> ())? = nil) {
group._broker.leaveGroup(
_group.id,
memberId: memberId,
clientId: _group._clientId,
callback: callback
)
}
/**
Issue a heartbeat request.
- Parameter callback: called when the heartbeat request has successfully completed
*/
func heartbeat(_ callback: (() -> ())? = nil) {
group._broker.heartbeatRequest(
_group.id,
generationId:_group._generationId,
memberId: memberId,
callback: callback
)
}
}
|
b4daebaae83909171ee44ceb9a2bb499
| 21.468571 | 108 | 0.561038 | false | false | false | false |
Noobish1/KeyedMapper
|
refs/heads/master
|
Playgrounds/KeyedMapper.playground/Contents.swift
|
mit
|
1
|
import UIKit
import KeyedMapper
// Convertible
extension NSTimeZone: Convertible {
public static func fromMap(_ value: Any) throws -> NSTimeZone {
guard let name = value as? String else {
throw MapperError.convertible(value: value, expectedType: String.self)
}
guard let timeZone = self.init(name: name) else {
throw MapperError.custom(field: nil, message: "Unsupported timezone \(name)")
}
return timeZone
}
}
// NilConvertible
enum NilConvertibleEnum {
case something
case nothing
}
extension NilConvertibleEnum: NilConvertible {
static func fromMap(_ value: Any?) throws -> NilConvertibleEnum {
if let _ = value {
return .something
} else {
return .nothing
}
}
}
// DefaultConvertible
enum DefaultConvertibleEnum: Int, DefaultConvertible {
case firstCase = 0
}
// Mappable
struct SubObject {
let property: String
}
extension SubObject: Mappable {
enum Key: String, JSONKey {
case property
}
init(map: KeyedMapper<SubObject>) throws {
self.property = try map.from(.property)
}
}
extension SubObject: ReverseMappable {
func toKeyedJSON() -> [SubObject.Key : Any?] {
return [.property : property]
}
}
struct Object {
let property: String
let optionalProperty: String?
let convertibleProperty: NSTimeZone
let optionalConvertibleProperty: NSTimeZone?
let nilConvertibleProperty: NilConvertibleEnum
let arrayProperty: [String]
let optionalArrayProperty: [String]?
let mappableProperty: SubObject
let optionalMappableProperty: SubObject?
let defaultConvertibleProperty: DefaultConvertibleEnum
let optionalDefaultConvertibleProperty: DefaultConvertibleEnum?
let twoDArrayProperty: [[String]]
let optionalTwoDArrayProperty: [[String]]?
}
extension Object: Mappable {
enum Key: String, JSONKey {
case property
case optionalProperty
case convertibleProperty
case optionalConvertibleProperty
case nilConvertibleProperty
case arrayProperty
case optionalArrayProperty
case mappableProperty
case optionalMappableProperty
case defaultConvertibleProperty
case optionalDefaultConvertibleProperty
case twoDArrayProperty
case optionalTwoDArrayProperty
}
init(map: KeyedMapper<Object>) throws {
self.property = try map.from(.property)
self.optionalProperty = map.optionalFrom(.optionalProperty)
self.convertibleProperty = try map.from(.convertibleProperty)
self.optionalConvertibleProperty = map.optionalFrom(.optionalConvertibleProperty)
self.nilConvertibleProperty = try map.from(.nilConvertibleProperty)
self.arrayProperty = try map.from(.arrayProperty)
self.optionalArrayProperty = map.optionalFrom(.optionalArrayProperty)
self.mappableProperty = try map.from(.mappableProperty)
self.optionalMappableProperty = map.optionalFrom(.optionalMappableProperty)
self.defaultConvertibleProperty = try map.from(.defaultConvertibleProperty)
self.optionalDefaultConvertibleProperty = map.optionalFrom(.optionalDefaultConvertibleProperty)
self.twoDArrayProperty = try map.from(.twoDArrayProperty)
self.optionalTwoDArrayProperty = map.optionalFrom(.optionalTwoDArrayProperty)
}
}
let JSON: NSDictionary = [
"property" : "propertyValue",
"convertibleProperty" : NSTimeZone(forSecondsFromGMT: 0).abbreviation as Any,
"arrayProperty" : ["arrayPropertyValue1", "arrayPropertyValue2"],
"mappableProperty" : ["property" : "propertyValue"],
"defaultConvertibleProperty" : DefaultConvertibleEnum.firstCase.rawValue,
"twoDArrayProperty" : [["twoDArrayPropertyValue1"], ["twoDArrayPropertyValue2"]]
]
let object = try Object.from(JSON)
print(object)
// ReverseMappable
extension Object: ReverseMappable {
func toKeyedJSON() -> [Object.Key : Any?] {
return [
.property : property,
.optionalProperty : optionalProperty,
.convertibleProperty : convertibleProperty,
.optionalConvertibleProperty : optionalConvertibleProperty,
.nilConvertibleProperty : nilConvertibleProperty,
.arrayProperty : arrayProperty,
.optionalArrayProperty : optionalArrayProperty,
.mappableProperty : mappableProperty.toJSON(),
.optionalMappableProperty : optionalMappableProperty?.toJSON(),
.defaultConvertibleProperty : defaultConvertibleProperty,
.optionalDefaultConvertibleProperty : optionalDefaultConvertibleProperty,
.twoDArrayProperty : twoDArrayProperty,
.optionalTwoDArrayProperty : optionalTwoDArrayProperty
]
}
}
let outJSON = object.toJSON()
print(outJSON)
|
77be04e822a8da2e31431e843da852e3
| 31.368421 | 103 | 0.7 | false | false | false | false |
calebd/swift
|
refs/heads/master
|
stdlib/public/core/Print.swift
|
apache-2.0
|
8
|
//===--- Print.swift ------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Writes the textual representations of the given items into the standard
/// output.
///
/// You can pass zero or more items to the `print(_:separator:terminator:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a string,
/// a closed range of integers, and a group of floating-point values to
/// standard output:
///
/// print("One two three four five")
/// // Prints "One two three four five"
///
/// print(1...5)
/// // Prints "1...5"
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `print(_:separator:terminator:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// for n in 1...5 {
/// print(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
@inline(never)
@_semantics("stdlib_binary_only")
public func print(
_ items: Any...,
separator: String = " ",
terminator: String = "\n"
) {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_print(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_print(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the standard output.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:)` function. The textual representation
/// for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints the debugging
/// representation of a string, a closed range of integers, and a group of
/// floating-point values to standard output:
///
/// debugPrint("One two three four five")
/// // Prints "One two three four five"
///
/// debugPrint(1...5)
/// // Prints "CountableClosedRange(1...5)"
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `debugPrint(_:separator:terminator:)` includes
/// a newline by default. To print the items without a trailing newline, pass
/// an empty string as `terminator`.
///
/// for n in 1...5 {
/// debugPrint(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
@inline(never)
@_semantics("stdlib_binary_only")
public func debugPrint(
_ items: Any...,
separator: String = " ",
terminator: String = "\n") {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items into the given output
/// stream.
///
/// You can pass zero or more items to the `print(_:separator:terminator:to:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a closed
/// range of integers to a string:
///
/// var range = "My range: "
/// print(1...5, to: &range)
/// // range == "My range: 1...5\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `print(_:separator:terminator:to:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// print(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
@inline(__always)
public func print<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_print(items, separator: separator, terminator: terminator, to: &output)
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the given output stream.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:to:)` function. The textual
/// representation for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints a closed range of
/// integers to a string:
///
/// var range = "My range: "
/// debugPrint(1...5, to: &range)
/// // range == "My range: CountableClosedRange(1...5)\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `debugPrint(_:separator:terminator:to:)`
/// includes a newline by default. To print the items without a trailing
/// newline, pass an empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// debugPrint(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
@inline(__always)
public func debugPrint<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
@_versioned
@inline(never)
@_semantics("stdlib_binary_only")
internal func _print<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_print_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
@_versioned
@inline(never)
@_semantics("stdlib_binary_only")
internal func _debugPrint<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_debugPrint_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
//===----------------------------------------------------------------------===//
//===--- Migration Aids ---------------------------------------------------===//
@available(*, unavailable, renamed: "print(_:separator:terminator:to:)")
public func print<Target : TextOutputStream>(
_ items: Any...,
separator: String = "",
terminator: String = "",
toStream output: inout Target
) {}
@available(*, unavailable, renamed: "debugPrint(_:separator:terminator:to:)")
public func debugPrint<Target : TextOutputStream>(
_ items: Any...,
separator: String = "",
terminator: String = "",
toStream output: inout Target
) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'print((...), terminator: \"\")'")
public func print<T>(_: T, appendNewline: Bool = true) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false': 'debugPrint((...), terminator: \"\")'")
public func debugPrint<T>(_: T, appendNewline: Bool = true) {}
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'")
public func print<T>(_: T, _: inout TextOutputStream) {}
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'debugPrint((...), to: &...))'")
public func debugPrint<T>(_: T, _: inout TextOutputStream) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'print((...), terminator: \"\", to: &...)'")
public func print<T>(_: T, _: inout TextOutputStream, appendNewline: Bool = true) {}
@available(*, unavailable, message: "Please use 'terminator: \"\"' instead of 'appendNewline: false' and use the 'to' label for the target stream: 'debugPrint((...), terminator: \"\", to: &...)'")
public func debugPrint<T>(
_: T, _: inout TextOutputStream, appendNewline: Bool = true
) {}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
|
6ecf6482c3e8bf8f70925e41e63224c5
| 35.306931 | 196 | 0.604127 | false | false | false | false |
AnRanScheme/magiGlobe
|
refs/heads/master
|
magi/magiGlobe/magiGlobe/Classes/Tool/Extension/Foundation/URLSession/URLSession+SynchronousTask.swift
|
mit
|
1
|
//
// URLSession+SynchronousTask.swift
// swift-magic
//
// Created by 安然 on 17/2/15.
// Copyright © 2017年 安然. All rights reserved.
//
import Foundation
public extension URLSession{
// MARK: - send data
public func m_sendSynchronousDataTask(with url: URL) -> (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) {
return self.m_sendSynchronousDataTask(with: URLRequest(url: url))
}
public func m_sendSynchronousDataTask(with request: URLRequest) -> (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) {
let semaphore = DispatchSemaphore(value: 0)
var currentReturn: (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) = (nil,nil,nil)
self.dataTask(with: request) { (_ taskData: Data?, _ taskResponse: URLResponse?, _ taskError: Error?) in
currentReturn.taskData = taskData
currentReturn.taskResponse = taskResponse
currentReturn.taskError = taskError
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: .distantFuture)
return currentReturn
}
// MARK: - download data
public func m_sendSynchronousDownloadTaskWithURL(with url: URL) -> (taskLocation: URL?, taskResponse: URLResponse?, taskError: Error?) {
return self.m_sendSynchronousDownloadTaskWithRequest(with: URLRequest(url: url))
}
public func m_sendSynchronousDownloadTaskWithRequest(with request: URLRequest) -> (taskLocation: URL?, taskResponse: URLResponse?, taskError: Error?) {
let semaphore = DispatchSemaphore(value: 0)
var currentReturn: (taskLocation: URL?, taskResponse: URLResponse?, taskError: Error?) = (nil,nil,nil)
self.downloadTask(with: request) { (taskLocation: URL?, taskResponse: URLResponse?, taskError: Error?) in
currentReturn.taskLocation = taskLocation
currentReturn.taskResponse = taskResponse
currentReturn.taskError = taskError
semaphore.signal()
}
_ = semaphore.wait(timeout: .distantFuture)
return currentReturn
}
// MARK: - update data
public func m_sendSynchronousUploadTaskWithRequest(with request: URLRequest, fromFile fileURL: URL) -> (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) {
return self.m_sendSynchronousUploadTaskWithRequest(with: request, fromData: try? Data(contentsOf: fileURL))
}
public func m_sendSynchronousUploadTaskWithRequest(with request: URLRequest, fromData bodyData: Data?) -> (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) {
let semaphore = DispatchSemaphore(value: 0)
var currentReturn: (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) = (nil,nil,nil)
self.uploadTask(with: request, from: bodyData) { (taskData: Data?, taskResponse: URLResponse?, taskError: Error?) in
currentReturn.taskData = taskData
currentReturn.taskResponse = taskResponse
currentReturn.taskError = taskError
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: .distantFuture)
return currentReturn
}
}
|
8418680c58786cf64ec32a0a40a6fdbe
| 44.492958 | 178 | 0.671827 | false | false | false | false |
SteveClement/Swifter
|
refs/heads/master
|
SwifterDemoiOS/TweetsViewController.swift
|
mit
|
3
|
//
// TweetsViewController.swift
// SwifterDemoiOS
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
import SwifteriOS
class TweetsViewController: UITableViewController {
var tweets : [JSONValue] = []
override func viewWillLayoutSubviews()
{
super.viewWillLayoutSubviews()
self.title = "Timeline"
self.tableView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, 0, 0)
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, 0, 0)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
cell.textLabel?.text = tweets[indexPath.row]["text"].string
return cell
}
}
|
4d335444fc917ed08c988f61c456440e
| 36.206897 | 118 | 0.725209 | false | false | false | false |
capstone411/SHAF
|
refs/heads/master
|
Capstone/IOS_app/SHAF/SHAF/FirstViewController.swift
|
mit
|
1
|
//
// FirstViewController.swift
// SHAF
//
// Created by Ahmed Abdulkareem on 4/12/16.
// Copyright © 2016 Ahmed Abdulkareem. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var buttonActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var bluetoothTable: UITableView!
@IBOutlet weak var connectButton: UIButton!
var selected_device = 0;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.bluetoothTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "BLCell")
// to update table view notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FirstViewController.loadList(_:)),name:"discoveredPeriph", object: nil)
// notify when connected
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FirstViewController.periphConnected(_:)),name:"periphConnected", object: nil)
self.connectButton.enabled = false
// activity view in the connect button
self.buttonActivityIndicator.hidden = true
BLEDiscovery // start bluetooth
}
// load bluetooth table
func loadList(notification: NSNotification) {
dispatch_sync(dispatch_get_main_queue()) {
//load data of table
self.bluetoothTable.reloadData()
}
}
// executes when peripheral is connected
func periphConnected(notification: NSNotification) {
dispatch_sync(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("selectGoalIdentifier", sender: nil)
// stop activity indicator
let cells = self.bluetoothTable.visibleCells as! [BluetoothTableCellTableViewCell]
let cell = cells[self.selected_device]
cell.indicator.stopAnimating()
self.buttonActivityIndicator.hidden = true
self.buttonActivityIndicator.stopAnimating()
}
}
@IBAction func connectButton(sender: AnyObject) {
// connect to peripheral
BLEDiscovery.connect(self.selected_device)
// start activitiy indicator
let cells = self.bluetoothTable.visibleCells as! [BluetoothTableCellTableViewCell]
let currCell = cells[self.selected_device]
currCell.indicator.startAnimating()
self.buttonActivityIndicator.hidden = false
self.buttonActivityIndicator.startAnimating() // for connect button
// disable connect button
self.connectButton.enabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return BLEDiscovery.devicesDiscovered.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : BluetoothTableCellTableViewCell = self.bluetoothTable.dequeueReusableCellWithIdentifier("BLCell")! as! BluetoothTableCellTableViewCell
let cellName = BLEDiscovery.devicesDiscovered[indexPath.row]
cell.textLabel?.text = cellName
// check if this is the bluetooth device and add
// check mark next to it
if cellName == "SHAF Bluetooth" {
cell.checkMarkImage.hidden = false
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.connectButton.enabled = true // enable connect button if not already
self.selected_device = indexPath.row // this is the index of selected device
}
}
|
0a9b4dc7614874a45a4059cb86c84497
| 35.633028 | 160 | 0.670924 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.