Commit a6ae3833 by Daniel Dahan

removed files until refactor is done

parent bdd34155
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import AVFoundation
@objc(PreviewDelegate)
public protocol PreviewDelegate {
optional func previewTappedToFocusAt(preview: Preview, point: CGPoint)
optional func previewTappedToExposeAt(preview: Preview, point: CGPoint)
optional func previewTappedToReset(preview: Preview, focus: UIView, exposure: UIView)
}
public class Preview: UIView {
/**
:name: boxBounds
:description: A static property that sets the initial size of the focusBox and exposureBox properties.
*/
static public var boxBounds: CGRect = CGRectMake(0, 0, 150, 150)
/**
:name: delegate
:description: An optional instance of PreviewDelegate to handle events that are triggered during various
stages of engagement.
*/
public weak var delegate: PreviewDelegate?
/**
:name: tapToFocusEnabled
:description: A mutator and accessor that enables and disables tap to focus gesture.
*/
public var tapToFocusEnabled: Bool {
get {
return singleTapRecognizer!.enabled
}
set(value) {
singleTapRecognizer!.enabled = value
}
}
/**
:name: tapToExposeEnabled
:description: A mutator and accessor that enables and disables tap to expose gesture.
*/
public var tapToExposeEnabled: Bool {
get {
return doubleTapRecognizer!.enabled
}
set(value) {
doubleTapRecognizer!.enabled = value
}
}
//
// override for layerClass
//
override public class func layerClass() -> AnyClass {
return AVCaptureVideoPreviewLayer.self
}
/**
:name: session
:description: A mutator and accessor for the preview AVCaptureSession value.
*/
public var session: AVCaptureSession {
get {
return (layer as! AVCaptureVideoPreviewLayer).session
}
set(value) {
(layer as! AVCaptureVideoPreviewLayer).session = value
}
}
/**
:name: focusBox
:description: An optional UIView for the focusBox animation. This is used when the
tapToFocusEnabled property is set to true.
*/
public var focusBox: UIView?
/**
:name: exposureBox
:description: An optional UIView for the exposureBox animation. This is used when the
tapToExposeEnabled property is set to true.
*/
public var exposureBox: UIView?
//
// :name: singleTapRecognizer
// :description: Gesture recognizer for single tap.
//
private var singleTapRecognizer: UITapGestureRecognizer?
//
// :name: doubleTapRecognizer
// :description: Gesture recognizer for double tap.
//
private var doubleTapRecognizer: UITapGestureRecognizer?
//
// :name: doubleDoubleTapRecognizer
// :description: Gesture recognizer for double/double tap.
//
private var doubleDoubleTapRecognizer: UITapGestureRecognizer?
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
public override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
public init() {
super.init(frame: CGRectZero)
translatesAutoresizingMaskIntoConstraints = false
prepareView()
}
//
// :name: handleSingleTap
//
internal func handleSingleTap(recognizer: UIGestureRecognizer) {
let point: CGPoint = recognizer.locationInView(self)
runBoxAnimationOnView(focusBox, point: point)
delegate?.previewTappedToFocusAt?(self, point: captureDevicePointForPoint(point))
}
//
// :name: handleDoubleTap
//
internal func handleDoubleTap(recognizer: UIGestureRecognizer) {
let point: CGPoint = recognizer.locationInView(self)
runBoxAnimationOnView(exposureBox, point: point)
delegate?.previewTappedToExposeAt?(self, point: captureDevicePointForPoint(point))
}
//
// :name: handleDoubleDoubleTap
//
internal func handleDoubleDoubleTap(recognizer: UIGestureRecognizer) {
runResetAnimation()
}
//
// :name: prepareView
// :description: Common setup for view.
//
private func prepareView() {
let captureLayer: AVCaptureVideoPreviewLayer = layer as! AVCaptureVideoPreviewLayer
captureLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
singleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
singleTapRecognizer!.numberOfTapsRequired = 1
doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
doubleTapRecognizer!.numberOfTapsRequired = 2
doubleDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleDoubleTap:")
doubleDoubleTapRecognizer!.numberOfTapsRequired = 2
doubleDoubleTapRecognizer!.numberOfTouchesRequired = 2
addGestureRecognizer(singleTapRecognizer!)
addGestureRecognizer(doubleTapRecognizer!)
addGestureRecognizer(doubleDoubleTapRecognizer!)
singleTapRecognizer!.requireGestureRecognizerToFail(doubleTapRecognizer!)
focusBox = viewWithColor(.redColor())
exposureBox = viewWithColor(.blueColor())
addSubview(focusBox!)
addSubview(exposureBox!)
}
//
// :name: viewWithColor
// :description: Initializes a UIView with a set UIColor.
//
private func viewWithColor(color: UIColor) -> UIView {
let view: UIView = UIView(frame: Preview.boxBounds)
view.backgroundColor = MaterialTheme.color.clear.base
view.layer.borderColor = color.CGColor
view.layer.borderWidth = 5
view.hidden = true
return view
}
//
// :name: runBoxAnimationOnView
// :description: Runs the animation used for focusBox and exposureBox on single and double
// taps respectively at a given point.
//
private func runBoxAnimationOnView(view: UIView!, point: CGPoint) {
view.center = point
view.hidden = false
UIView.animateWithDuration(0.15, delay: 0, options: .CurveEaseInOut, animations: { _ in
view.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1)
}) { _ in
let delayInSeconds: Double = 0.5
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
view.hidden = true
view.transform = CGAffineTransformIdentity
}
}
}
//
// :name: captureDevicePointForPoint
// :description: Interprets the correct point from touch to preview layer.
//
private func captureDevicePointForPoint(point: CGPoint) -> CGPoint {
let previewLayer: AVCaptureVideoPreviewLayer = layer as! AVCaptureVideoPreviewLayer
return previewLayer.captureDevicePointOfInterestForPoint(point)
}
//
// :name: runResetAnimation
// :description: Executes the reset animation for focus and exposure.
//
private func runResetAnimation() {
if !tapToFocusEnabled && !tapToExposeEnabled {
return
}
let previewLayer: AVCaptureVideoPreviewLayer = layer as! AVCaptureVideoPreviewLayer
let centerPoint: CGPoint = previewLayer.pointForCaptureDevicePointOfInterest(CGPointMake(0.5, 0.5))
focusBox!.center = centerPoint
exposureBox!.center = centerPoint
exposureBox!.transform = CGAffineTransformMakeScale(1.2, 1.2)
focusBox!.hidden = false
exposureBox!.hidden = false
UIView.animateWithDuration(0.15, delay: 0, options: .CurveEaseInOut, animations: { _ in
self.focusBox!.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1)
self.exposureBox!.layer.transform = CATransform3DMakeScale(0.7, 0.7, 1)
}) { _ in
let delayInSeconds: Double = 0.5
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
self.focusBox!.hidden = true
self.exposureBox!.hidden = true
self.focusBox!.transform = CGAffineTransformIdentity
self.exposureBox!.transform = CGAffineTransformIdentity
self.delegate?.previewTappedToReset?(self, focus: self.focusBox!, exposure: self.exposureBox!)
}
}
}
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class FabButton : MaterialButton {
//
// :name: prepareButton
//
internal override func prepareView() {
super.prepareView()
setTitleColor(MaterialTheme.color.white.base, forState: .Normal)
backgroundColor = MaterialTheme.color.red.darken1
contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
}
//
// :name: prepareButton
//
internal override func prepareButton() {
super.prepareButton()
prepareShadow()
backgroundColorView.layer.cornerRadius = bounds.width / 2
}
//
// :name: pulseBegan
//
internal override func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent?) {
super.pulseBegan(touches, withEvent: event)
UIView.animateWithDuration(0.3, animations: {
self.pulseView!.transform = CGAffineTransformMakeScale(3, 3)
self.transform = CGAffineTransformMakeScale(1.1, 1.1)
})
}
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class FlatButton : MaterialButton {
//
// :name: prepareView
//
internal override func prepareView() {
super.prepareView()
titleLabel!.font = Roboto.regular
setTitleColor(MaterialTheme.color.blueGrey.darken4, forState: .Normal)
pulseColor = MaterialTheme.color.blueGrey.lighten3
backgroundColor = MaterialTheme.color.clear.base
contentEdgeInsets = UIEdgeInsetsMake(MaterialTheme.buttonVerticalInset, MaterialTheme.buttonHorizontalInset, MaterialTheme.buttonVerticalInset, MaterialTheme.buttonHorizontalInset)
}
//
// :name: prepareButton
//
internal override func prepareButton() {
super.prepareButton()
backgroundColorView.layer.cornerRadius = 3
}
//
// :name: pulseBegan
//
internal override func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent?) {
super.pulseBegan(touches, withEvent: event)
UIView.animateWithDuration(0.3, animations: {
self.pulseView!.transform = CGAffineTransformMakeScale(4, 4)
self.transform = CGAffineTransformMakeScale(1.05, 1.05)
})
}
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public struct Layout {
/**
:name: width
*/
public static func width(parent: UIView, child: UIView, width: CGFloat = 0) {
let metrics: Dictionary<String, AnyObject> = ["width" : width]
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:[child(width)]", options: [], metrics: metrics, views: views))
}
/**
:name: height
*/
public static func height(parent: UIView, child: UIView, height: CGFloat = 0) {
let metrics: Dictionary<String, AnyObject> = ["height" : height]
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("V:[child(height)]", options: [], metrics: metrics, views: views))
}
/**
:name: size
*/
public static func size(parent: UIView, child: UIView, width: CGFloat = 0, height: CGFloat = 0) {
Layout.width(parent, child: child, width: width)
Layout.height(parent, child: child, height: height)
}
/**
:name: expandToParent
*/
public static func expandToParent(parent: UIView, child: UIView) {
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:|[child]|", options: [], metrics: nil, views: views))
parent.addConstraints(constraint("V:|[child]|", options: [], metrics: nil, views: views))
}
/**
:name: expandToParentHorizontally
*/
public static func expandToParentHorizontally(parent: UIView, child: UIView) {
expandToParentHorizontallyWithPad(parent, child: child, left: 0, right: 0)
}
/**
:name: expandToParentHorizontallyWithPad
*/
public static func expandToParentHorizontallyWithPad(parent: UIView, child: UIView, left: CGFloat = 0, right: CGFloat = 0) {
parent.addConstraints(constraint("H:|-(left)-[child]-(right)-|", options: [], metrics: ["left": left, "right": right], views: ["child" : child]))
}
/**
:name: expandToParentVertically
*/
public static func expandToParentVertically(parent: UIView, child: UIView) {
expandToParentVerticallyWithPad(parent, child: child, top: 0, bottom: 0)
}
/**
:name: expandToParentVerticallyWithPad
*/
public static func expandToParentVerticallyWithPad(parent: UIView, child: UIView, top: CGFloat = 0, bottom: CGFloat = 0) {
parent.addConstraints(constraint("V:|-(top)-[child]-(bottom)-|", options: [], metrics: ["bottom": bottom, "top": top], views: ["child" : child]))
}
/**
:name: expandToParentWithPad
*/
public static func expandToParentWithPad(parent: UIView, child: UIView, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) {
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:|-(left)-[child]-(right)-|", options: [], metrics: ["left": left, "right": right], views: views))
parent.addConstraints(constraint("V:|-(top)-[child]-(bottom)-|", options: [], metrics: ["bottom": bottom, "top": top], views: views))
}
/**
:name: alignFromTopLeft
*/
public static func alignFromTopLeft(parent: UIView, child: UIView, top: CGFloat = 0, left: CGFloat = 0) {
let metrics: Dictionary<String, AnyObject> = ["top" : top, "left" : left]
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:|-(left)-[child]", options: [], metrics: metrics, views: views))
parent.addConstraints(constraint("V:|-(top)-[child]", options: [], metrics: metrics, views: views))
}
/**
:name: alignFromTopRight
*/
public static func alignFromTopRight(parent: UIView, child: UIView, top: CGFloat = 0, right: CGFloat = 0) {
let metrics: Dictionary<String, AnyObject> = ["top" : top, "right" : right]
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:[child]-(right)-|", options: [], metrics: metrics, views: views))
parent.addConstraints(constraint("V:|-(top)-[child]", options: [], metrics: metrics, views: views))
}
/**
:name: alignFromBottomLeft
*/
public static func alignFromBottomLeft(parent: UIView, child: UIView, bottom: CGFloat = 0, left: CGFloat = 0) {
let metrics: Dictionary<String, AnyObject> = ["bottom" : bottom, "left" : left]
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:|-(left)-[child]", options: [], metrics: metrics, views: views))
parent.addConstraints(constraint("V:[child]-(bottom)-|", options: [], metrics: metrics, views: views))
}
/**
:name: alignFromBottomRight
*/
public static func alignFromBottomRight(parent: UIView, child: UIView, bottom: CGFloat = 0, right: CGFloat = 0) {
let metrics: Dictionary<String, AnyObject> = ["bottom" : bottom, "right" : right]
let views: Dictionary<String, AnyObject> = ["child" : child]
parent.addConstraints(constraint("H:[child]-(right)-|", options: [], metrics: metrics, views: views))
parent.addConstraints(constraint("V:[child]-(bottom)-|", options: [], metrics: metrics, views: views))
}
/**
:name: alignFromTop
*/
public static func alignFromTop(parent: UIView, child: UIView, top: CGFloat = 0) {
parent.addConstraints(constraint("V:|-(top)-[child]", options: [], metrics: ["top" : top], views: ["child" : child]))
}
/**
:name: alignFromLeft
*/
public static func alignFromLeft(parent: UIView, child: UIView, left: CGFloat = 0) {
parent.addConstraints(constraint("H:|-(left)-[child]", options: [], metrics: ["left" : left], views: ["child" : child]))
}
/**
:name: alignFromBottom
*/
public static func alignFromBottom(parent: UIView, child: UIView, bottom: CGFloat = 0) {
parent.addConstraints(constraint("V:[child]-(bottom)-|", options: [], metrics: ["bottom" : bottom], views: ["child" : child]))
}
/**
:name: alignFromRight
*/
public static func alignFromRight(parent: UIView, child: UIView, right: CGFloat = 0) {
parent.addConstraints(constraint("H:[child]-(right)-|", options: [], metrics: ["right" : right], views: ["child" : child]))
}
/**
:name: alignAllSides
*/
public static func alignAllSides(parent: UIView, child: UIView) {
expandToParent(parent, child: child)
}
/**
:name: constraint
*/
public static func constraint(format: String, options: NSLayoutFormatOptions, metrics: Dictionary<String, AnyObject>?, views: Dictionary<String, AnyObject>) -> Array<NSLayoutConstraint> {
return NSLayoutConstraint.constraintsWithVisualFormat(
format,
options: options,
metrics: metrics,
views: views
)
}
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class MaterialButton : UIButton {
//
// :name: backgroundColorView
//
internal lazy var backgroundColorView: UIView = UIView()
//
// :name: pulseView
//
internal var pulseView: UIView?
/**
:name: backgroundColor
*/
public override var backgroundColor: UIColor? {
get {
return backgroundColorView.backgroundColor
}
set(value) {
backgroundColorView.backgroundColor = value
}
}
/**
:name: pulseColor
*/
public var pulseColor: UIColor? = MaterialTheme.color.white.base
/**
:name: init
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
/**
:name: init
*/
public required override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
/**
:name: init
*/
public convenience init() {
self.init(frame: CGRectZero)
}
/**
:name: touchesBegan
*/
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
pulseBegan(touches, withEvent: event)
}
/**
:name: touchesEnded
*/
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
shrink()
pulseEnded(touches, withEvent: event)
}
/**
:name: touchesCancelled
*/
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
shrink()
pulseEnded(touches, withEvent: event)
}
/**
:name: drawRect
*/
final public override func drawRect(rect: CGRect) {
prepareBackgroundColorView()
prepareButton()
}
//
// :name: prepareView
//
internal func prepareView() {
translatesAutoresizingMaskIntoConstraints = false
}
//
// :name: prepareButton
//
internal func prepareButton() {}
//
// :name: prepareShadow
//
internal func prepareShadow() {
layer.shadowColor = MaterialTheme.color.black.base.CGColor
layer.shadowOffset = CGSizeMake(0.1, 0.1)
layer.shadowOpacity = 0.4
layer.shadowRadius = 2
}
//
// :name: pulseBegan
//
internal func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent?) {
pulseView = UIView(frame: CGRectMake(0, 0, bounds.height, bounds.height))
pulseView!.layer.cornerRadius = bounds.height / 2
pulseView!.center = (touches.first as! UITouch).locationInView(self)
pulseView!.backgroundColor = pulseColor?.colorWithAlphaComponent(0.3)
backgroundColorView.addSubview(pulseView!)
}
//
// :name: pulseEnded
//
internal func pulseEnded(touches: Set<NSObject>?, withEvent event: UIEvent?) {
UIView.animateWithDuration(0.3,
animations: { _ in
self.pulseView?.alpha = 0
}
) { _ in
self.pulseView?.removeFromSuperview()
self.pulseView = nil
}
}
//
// :name: prepareBackgroundColorView
//
private func prepareBackgroundColorView() {
backgroundColorView.translatesAutoresizingMaskIntoConstraints = false
backgroundColorView.layer.masksToBounds = true
backgroundColorView.clipsToBounds = true
backgroundColorView.userInteractionEnabled = false
insertSubview(backgroundColorView, atIndex: 0)
Layout.expandToParent(self, child: backgroundColorView)
}
//
// :name: shrink
//
private func shrink() {
UIView.animateWithDuration(0.3,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 10,
options: [],
animations: {
self.transform = CGAffineTransformIdentity
},
completion: nil
)
}
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class MaterialCardView : UIView {
//
// :name: backgroundColorView
//
internal lazy var backgroundColorView: UIView = UIView()
//
// :name: pulseViewContainer
//
internal lazy var pulseViewContainer: UIView = UIView()
//
// :name: pulseView
//
internal var pulseView: UIView?
/**
:name: backgroundColor
*/
public override var backgroundColor: UIColor? {
get {
return backgroundColorView.backgroundColor
}
set(value) {
backgroundColorView.backgroundColor = value
}
}
/**
:name: pulseColor
*/
public var pulseColor: UIColor? = MaterialTheme.color.blueGrey.lighten3
/**
:name: init
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
/**
:name: init
*/
public required override init(frame: CGRect) {
super.init(frame: frame)
prepareView()
}
/**
:name: init
*/
public convenience init() {
self.init(frame: CGRectZero)
}
/**
:name: touchesBegan
*/
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
pulseBegan(touches, withEvent: event)
}
/**
:name: touchesEnded
*/
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
shrink()
pulseEnded(touches, withEvent: event)
}
/**
:name: touchesCancelled
*/
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
shrink()
pulseEnded(touches, withEvent: event)
}
//
// :name: prepareView
//
internal func prepareView() {
translatesAutoresizingMaskIntoConstraints = false
prepareBackgroundColorView()
preparePulseViewContainer()
}
//
// :name: prepareShadow
//
internal func prepareShadow() {
layer.shadowColor = MaterialTheme.color.black.base.CGColor
layer.shadowOffset = CGSizeMake(0.1, 0.1)
layer.shadowOpacity = 0.4
layer.shadowRadius = 2
}
//
// :name: removeShadow
//
internal func removeShadow() {
layer.shadowColor = MaterialTheme.color.clear.base.CGColor
layer.shadowOffset = CGSizeMake(0, 0)
layer.shadowOpacity = 0
layer.shadowRadius = 0
}
//
// :name: layoutSubviews
//
public override func layoutSubviews() {
super.layoutSubviews()
layer.shadowPath = UIBezierPath(rect: bounds).CGPath
}
//
// :name: pulseBegan
//
internal func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent?) {
let width: CGFloat = bounds.size.width / 3
pulseView = UIView(frame: CGRectMake(0, 0, width, width))
pulseView!.layer.cornerRadius = width / 2
pulseView!.center = (touches.first as! UITouch).locationInView(self)
pulseView!.backgroundColor = pulseColor?.colorWithAlphaComponent(0.3)
addSubview(pulseViewContainer)
Layout.expandToParent(self, child: pulseViewContainer)
pulseViewContainer.addSubview(pulseView!)
UIView.animateWithDuration(0.3, animations: {
self.pulseView!.transform = CGAffineTransformMakeScale(3, 3)
self.transform = CGAffineTransformMakeScale(1.05, 1.05)
}, completion: nil)
}
//
// :name: pulseEnded
//
internal func pulseEnded(touches: Set<NSObject>?, withEvent event: UIEvent?) {
UIView.animateWithDuration(0.3,
animations: { _ in
self.pulseView?.alpha = 0
}
) { _ in
self.pulseViewContainer.removeFromSuperview()
self.pulseView?.removeFromSuperview()
self.pulseView = nil
}
}
//
// :name: prepareBackgroundColorView
//
// We need this view so we can use the masksToBounds
// so the pulse doesn't animate off the button
private func prepareBackgroundColorView() {
backgroundColorView.translatesAutoresizingMaskIntoConstraints = false
backgroundColorView.layer.cornerRadius = 2
backgroundColorView.layer.masksToBounds = true
backgroundColorView.clipsToBounds = true
backgroundColorView.userInteractionEnabled = false
insertSubview(backgroundColorView, atIndex: 0)
Layout.expandToParent(self, child: backgroundColorView)
}
//
// :name: preparePulseViewContainer
//
// We need this view so we can use the masksToBounds
// so the pulse doesn't animate off the button
private func preparePulseViewContainer() {
pulseViewContainer.translatesAutoresizingMaskIntoConstraints = false
pulseViewContainer.layer.cornerRadius = 2
pulseViewContainer.layer.masksToBounds = true
pulseViewContainer.clipsToBounds = true
pulseViewContainer.userInteractionEnabled = false
}
//
// :name: shrink
//
private func shrink() {
UIView.animateWithDuration(0.3,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 10,
options: [],
animations: {
self.transform = CGAffineTransformIdentity
},
completion: nil
)
}
}
......@@ -18,12 +18,18 @@
import UIKit
public struct Roboto {
// font
public struct MaterialFont {
/**
:name: pointSize
*/
public static var pointSize: CGFloat = 16
/**
:name: thin
*/
public static var thin: UIFont {
return thinWithSize(MaterialTheme.font.pointSize)
return thinWithSize(MaterialFont.pointSize)
}
/**
......@@ -40,58 +46,58 @@ public struct Roboto {
:name: light
*/
public static var light: UIFont {
return lightWithSize(MaterialTheme.font.pointSize)
return lightWithSize(MaterialFont.pointSize)
}
/**
:name: lightWithSize
*/
public static func lightWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Light", size: size) {
return f
}
public static func lightWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Light", size: size) {
return f
}
return UIFont.systemFontOfSize(size)
}
}
/**
:name: regular
*/
public static var regular: UIFont {
return regularWithSize(MaterialTheme.font.pointSize)
return regularWithSize(MaterialFont.pointSize)
}
/**
:name: mediumWithSize
*/
public static func mediumWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Medium", size: size) {
return f
}
public static func mediumWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Medium", size: size) {
return f
}
return UIFont.systemFontOfSize(size)
}
}
/**
:name: medium
*/
public static var medium: UIFont {
return mediumWithSize(MaterialTheme.font.pointSize)
return mediumWithSize(MaterialFont.pointSize)
}
/**
:name: regularWithSize
*/
public static func regularWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Regular", size: size) {
return f
}
public static func regularWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Regular", size: size) {
return f
}
return UIFont.systemFontOfSize(size)
}
}
/**
:name: bold
*/
public static var bold: UIFont {
return boldWithSize(MaterialTheme.font.pointSize)
return boldWithSize(MaterialFont.pointSize)
}
/**
......@@ -103,4 +109,4 @@ public struct Roboto {
}
return UIFont.systemFontOfSize(size)
}
}
}
\ No newline at end of file
......@@ -66,66 +66,4 @@ public func MaterialGravityToString(gravity: MaterialGravity) -> String {
case .ResizeAspectFill:
return kCAGravityResizeAspectFill
}
}
// MaterialTheme
public extension MaterialTheme {
public struct view {}
public struct navigation {}
}
// view
public extension MaterialTheme.view {
// frame
public static var x: CGFloat = 0
public static let y: CGFloat = 0
public static let width: CGFloat = UIScreen.mainScreen().bounds.width
public static let height: CGFloat = UIScreen.mainScreen().bounds.height
// layer
public static let shadowColor: UIColor = MaterialTheme.color.blueGrey.darken4
public static let shadowOffset: CGSize = CGSizeMake(0.2, 0.2)
public static let shadowOpacity: Float = 0.5
public static let shadowRadius: CGFloat = 1
public static let masksToBounds: Bool = false
// color
public static let backgroudColor: UIColor = MaterialTheme.color.white.base
// interaction
public static let userInteractionEnabled: Bool = true
// image
public static let contentsGravity: MaterialGravity = .ResizeAspectFill
public static let contentsRect: CGRect = CGRectMake(0, 0, 1, 1)
public static let contentsScale: CGFloat = UIScreen.mainScreen().scale
}
// navigation
public extension MaterialTheme.navigation {
// frame
public static let x: CGFloat = MaterialTheme.view.x
public static let y: CGFloat = MaterialTheme.view.y
public static let width: CGFloat = MaterialTheme.view.width
public static let height: CGFloat = 70
// layer
public static let shadowColor: UIColor = MaterialTheme.view.shadowColor
public static let shadowOffset: CGSize = MaterialTheme.view.shadowOffset
public static let shadowOpacity: Float = MaterialTheme.view.shadowOpacity
public static let shadowRadius: CGFloat = MaterialTheme.view.shadowRadius
public static let masksToBounds: Bool = MaterialTheme.view.masksToBounds
// color
public static let backgroudColor: UIColor = MaterialTheme.color.blue.accent2
public static let lightContentStatusBar: Bool = true
// interaction
public static let userInteractionEnabled: Bool = false
// image
public static let contentsGravity: MaterialGravity = MaterialTheme.view.contentsGravity
public static let contentsRect: CGRect = MaterialTheme.view.contentsRect
public static let contentsScale: CGFloat = MaterialTheme.view.contentsScale
}
}
\ No newline at end of file
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
@objc(MaterialTextDelegate)
public protocol TextDelegate {
optional func textStorageWillProcessEdit(text: MaterialText, textStorage: MaterialTextStorage, string: String, range: NSRange)
optional func textStorageDidProcessEdit(text: MaterialText, textStorage: MaterialTextStorage, string: String, result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>)
}
@objc(MaterialText)
public class MaterialText: NSObject {
/**
:name: searchPattern
:description: A string representation of the regular expression that matches text within
the TextStorage string property. By default, the search pattern recognizes words and emoji
haracters beginning with hashtags.
*/
public var searchPattern: String = "(^|\\s)#[\\d\\w_\u{203C}\u{2049}\u{20E3}\u{2122}\u{2139}\u{2194}-\u{2199}\u{21A9}-\u{21AA}\u{231A}-\u{231B}\u{23E9}-\u{23EC}\u{23F0}\u{23F3}\u{24C2}\u{25AA}-\u{25AB}\u{25B6}\u{25C0}\u{25FB}-\u{25FE}\u{2600}-\u{2601}\u{260E}\u{2611}\u{2614}-\u{2615}\u{261D}\u{263A}\u{2648}-\u{2653}\u{2660}\u{2663}\u{2665}-\u{2666}\u{2668}\u{267B}\u{267F}\u{2693}\u{26A0}-\u{26A1}\u{26AA}-\u{26AB}\u{26BD}-\u{26BE}\u{26C4}-\u{26C5}\u{26CE}\u{26D4}\u{26EA}\u{26F2}-\u{26F3}\u{26F5}\u{26FA}\u{26FD}\u{2702}\u{2705}\u{2708}-\u{270C}\u{270F}\u{2712}\u{2714}\u{2716}\u{2728}\u{2733}-\u{2734}\u{2744}\u{2747}\u{274C}\u{274E}\u{2753}-\u{2755}\u{2757}\u{2764}\u{2795}-\u{2797}\u{27A1}\u{27B0}\u{2934}-\u{2935}\u{2B05}-\u{2B07}\u{2B1B}-\u{2B1C}\u{2B50}\u{2B55}\u{3030}\u{303D}\u{3297}\u{3299}\u{1F004}\u{1F0CF}\u{1F170}-\u{1F171}\u{1F17E}-\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E7}-\u{1F1EC}\u{1F1EE}-\u{1F1F0}\u{1F1F3}\u{1F1F5}\u{1F1F7}-\u{1F1FA}\u{1F201}-\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}-\u{1F251}\u{1F300}-\u{1F320}\u{1F330}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F380}-\u{1F393}\u{1F3A0}-\u{1F3C4}\u{1F3C6}-\u{1F3CA}\u{1F3E0}-\u{1F3F0}\u{1F400}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4F7}\u{1F4F9}-\u{1F4FC}\u{1F500}-\u{1F507}\u{1F509}-\u{1F53D}\u{1F550}-\u{1F567}\u{1F5FB}-\u{1F640}\u{1F645}-\u{1F64F}\u{1F680}-\u{1F68A}]+" {
didSet {
textStorage.searchExpression = try? NSRegularExpression(pattern: searchPattern, options: [])
}
}
/**
:name: textStorage
:description: Reference to wrapped NSTextStorage
*/
public let textStorage: MaterialTextStorage
/**
:name: delegate
:description: An optional instance of TextDelegate to handle text processing events.
*/
public weak var delegate: TextDelegate?
/**
:name: init
*/
public override init() {
textStorage = MaterialTextStorage()
super.init()
textStorage.searchExpression = try? NSRegularExpression(pattern: searchPattern, options: [])
textStorage.textStorageWillProcessEdit = { (textStorage: MaterialTextStorage, string: String, range: NSRange) -> Void in
self.delegate?.textStorageWillProcessEdit?(self, textStorage: textStorage, string: string, range: range)
}
textStorage.textStorageDidProcessEdit = { (textStorage: MaterialTextStorage, result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
self.delegate?.textStorageDidProcessEdit?(self, textStorage: textStorage, string: textStorage.string, result: result, flags: flags, stop: stop)
}
}
/**
:name: string
:description: Managed string value.
*/
public var string: String {
get {
return textStorage.string
}
}
/**
:name: matches
:description: An array of matches found in the TextStorage string property based on the
searchPattern property.
*/
public var matches: Array<String> {
get {
let results: Array<NSTextCheckingResult> = textStorage.searchExpression!.matchesInString(string, options: [], range: NSMakeRange(0, string.utf16.count))
return unique(results.map {(self.string as NSString).substringWithRange($0.range)})
}
}
/**
:name: unique
:description: Ensures a unique value in the matches return array.
*/
private func unique<S: SequenceType, E: Hashable where E == S.Generator.Element>(source: S) -> [E] {
var seen: [E:Bool] = [:]
return source.filter {nil == seen.updateValue(true, forKey: $0)}
}
}
\ No newline at end of file
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
internal typealias MaterialTextStorageWillProcessEdit = (MaterialTextStorage, String, NSRange) -> Void
internal typealias MaterialTextStorageDidProcessEdit = (MaterialTextStorage, NSTextCheckingResult?, NSMatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void
public class MaterialTextStorage: NSTextStorage {
/**
:name: store
:description: Acts as the model, storing the string value.
*/
private lazy var store: NSMutableAttributedString = NSMutableAttributedString()
/**
:name: searchExpression
:description: Matches text within the TextStorage string property.
*/
internal var searchExpression: NSRegularExpression?
/**
:name: textStorageWillProcessEdit
:description: If set, this block callback executes when there is a change in the TextStorage
string value.
*/
internal var textStorageWillProcessEdit: MaterialTextStorageWillProcessEdit?
/**
:name: textStorageDidProcessEdit
:description: If set, this block callback executes when a match is detected after a change in
the TextStorage string value.
*/
internal var textStorageDidProcessEdit: MaterialTextStorageDidProcessEdit?
/**
:name: init
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
:name: init
*/
public override init() {
super.init()
}
/**
:name: string
:description: Managed string value.
*/
override public var string: String {
get {
return store.string
}
}
/**
:name: processEditing
*/
public override func processEditing() {
let range: NSRange = (string as NSString).paragraphRangeForRange(editedRange)
textStorageWillProcessEdit?(self, string, range)
searchExpression!.enumerateMatchesInString(string, options: [], range: range) { (result: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
self.textStorageDidProcessEdit?(self, result, flags, stop)
}
super.processEditing()
}
/**
:name: attributesAtIndex
*/
public override func attributesAtIndex(location: Int, effectiveRange range: NSRangePointer) -> [String : AnyObject] {
return store.attributesAtIndex(location, effectiveRange: range)
}
/**
:name: replaceCharactersInRange
*/
public override func replaceCharactersInRange(range: NSRange, withString str: String) {
store.replaceCharactersInRange(range, withString: str)
edited(NSTextStorageEditActions.EditedCharacters, range: range, changeInLength: str.utf16.count - range.length)
}
/**
:name: setAttributes
*/
public override func setAttributes(attrs: [String : AnyObject]?, range: NSRange) {
store.setAttributes(attrs, range: range)
edited(NSTextStorageEditActions.EditedAttributes, range: range, changeInLength: 0)
}
}
\ No newline at end of file
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
// font
public extension MaterialTheme {
public struct font {
public static var pointSize: CGFloat = 16
}
}
\ No newline at end of file
......@@ -18,16 +18,65 @@
import UIKit
public struct MaterialTheme {}
public struct MaterialTheme {
public struct view {}
public struct navigation {}
}
// spacing
public extension MaterialTheme {
public static var cardVerticalInset: CGFloat = 16
public static var cardHorizontalInset: CGFloat = 16
// view
public extension MaterialTheme.view {
// frame
public static var x: CGFloat = 0
public static let y: CGFloat = 0
public static let width: CGFloat = UIScreen.mainScreen().bounds.width
public static let height: CGFloat = UIScreen.mainScreen().bounds.height
public static var buttonVerticalInset: CGFloat = 6
public static var buttonHorizontalInset: CGFloat = 16
// layer
public static let shadowColor: UIColor = MaterialColor.blueGrey.darken4
public static let shadowOffset: CGSize = CGSizeMake(0.2, 0.2)
public static let shadowOpacity: Float = 0.5
public static let shadowRadius: CGFloat = 1
public static let masksToBounds: Bool = false
public static var navigationVerticalInset: CGFloat = 8
public static var navigationHorizontalInset: CGFloat = 8
}
\ No newline at end of file
// color
public static let backgroudColor: UIColor = MaterialColor.white.color
// interaction
public static let userInteractionEnabled: Bool = true
// image
public static let contentsRect: CGRect = CGRectMake(0, 0, 1, 1)
public static let contentsCenter: CGRect = CGRectMake(0, 0, 1, 1)
public static let contentsScale: CGFloat = UIScreen.mainScreen().scale
public static let contentsGravity: MaterialGravity = .ResizeAspectFill
}
// navigation
public extension MaterialTheme.navigation {
// frame
public static let x: CGFloat = MaterialTheme.view.x
public static let y: CGFloat = MaterialTheme.view.y
public static let width: CGFloat = MaterialTheme.view.width
public static let height: CGFloat = 70
// layer
public static let shadowColor: UIColor = MaterialTheme.view.shadowColor
public static let shadowOffset: CGSize = MaterialTheme.view.shadowOffset
public static let shadowOpacity: Float = MaterialTheme.view.shadowOpacity
public static let shadowRadius: CGFloat = MaterialTheme.view.shadowRadius
public static let masksToBounds: Bool = MaterialTheme.view.masksToBounds
// color
public static let backgroudColor: UIColor = MaterialColor.blue.accent2
public static let lightContentStatusBar: Bool = true
// interaction
public static let userInteractionEnabled: Bool = false
// image
public static let contentsRect: CGRect = MaterialTheme.view.contentsRect
public static let contentsCenter: CGRect = MaterialTheme.view.contentsCenter
public static let contentsScale: CGFloat = MaterialTheme.view.contentsScale
public static let contentsGravity: MaterialGravity = MaterialTheme.view.contentsGravity
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class RaisedButton : MaterialButton {
//
// :name: prepareButton
//
internal override func prepareView() {
super.prepareView()
titleLabel!.font = Roboto.regular
setTitleColor(MaterialTheme.color.white.base, forState: .Normal)
backgroundColor = MaterialTheme.color.blue.accent2
contentEdgeInsets = UIEdgeInsetsMake(MaterialTheme.buttonVerticalInset, MaterialTheme.buttonHorizontalInset, MaterialTheme.buttonVerticalInset, MaterialTheme.buttonHorizontalInset)
}
//
// :name: prepareButton
//
internal override func prepareButton() {
super.prepareButton()
prepareShadow()
backgroundColorView.layer.cornerRadius = 3
}
//
// :name: pulseBegan
//
internal override func pulseBegan(touches: Set<NSObject>, withEvent event: UIEvent?) {
super.pulseBegan(touches, withEvent: event)
UIView.animateWithDuration(0.3, animations: {
self.pulseView!.transform = CGAffineTransformMakeScale(4, 4)
self.transform = CGAffineTransformMakeScale(1.05, 1.05)
})
}
}
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
public class TextView: UITextView {
//
// :name: layoutConstraints
//
internal lazy var layoutConstraints: Array<NSLayoutConstraint> = Array<NSLayoutConstraint>()
/**
:name: init
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareView()
}
/**
:name: init
*/
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
if CGRectZero == frame {
translatesAutoresizingMaskIntoConstraints = false
}
prepareView()
}
//
// :name: deinit
// :description: Notification observer removed from UITextView.
//
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidChangeNotification, object: nil)
}
/**
:name: placeholder
:description: The placeholder label string.
*/
public var placeholderLabel: UILabel? {
didSet {
if let p = placeholderLabel {
p.translatesAutoresizingMaskIntoConstraints = false
p.font = font
p.textAlignment = textAlignment
p.numberOfLines = 0
p.backgroundColor = MaterialTheme.color.clear.base
addSubview(p)
updateLabelConstraints()
textViewTextDidChange()
}
}
}
/**
:name: text
:description: When set, updates the placeholder text.
*/
public override var text: String! {
didSet {
textViewTextDidChange()
}
}
/**
:name: attributedText
:description: When set, updates the placeholder attributedText.
*/
public override var attributedText: NSAttributedString! {
didSet {
textViewTextDidChange()
}
}
/**
:name: textContainerInset
:description: When set, updates the placeholder constraints.
*/
public override var textContainerInset: UIEdgeInsets {
didSet {
updateLabelConstraints()
}
}
public override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel?.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2
}
//
// :name: textViewTextDidChange
// :description: Updates the label visibility when text is empty or not.
//
internal func textViewTextDidChange() {
if let p = placeholderLabel {
p.hidden = !text.isEmpty
}
}
//
// :name: prepareView
// :description: Sets up the common initilized values.
//
private func prepareView() {
// label needs to be added to the view
// hierarchy before setting insets
textContainerInset = UIEdgeInsetsMake(16, 16, 16, 16)
backgroundColor = MaterialTheme.color.clear.base
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewTextDidChange", name: UITextViewTextDidChangeNotification, object: nil)
updateLabelConstraints()
}
//
// :name: updateLabelConstraints
// :description: Updates the placeholder constraints.
//
private func updateLabelConstraints() {
if let p = placeholderLabel {
NSLayoutConstraint.deactivateConstraints(layoutConstraints)
layoutConstraints = Layout.constraint("H:|-(left)-[placeholderLabel]-(right)-|",
options: [],
metrics: [
"left": textContainerInset.left + textContainer.lineFragmentPadding,
"right": textContainerInset.right + textContainer.lineFragmentPadding
], views: [
"placeholderLabel": p
])
layoutConstraints += Layout.constraint("V:|-(top)-[placeholderLabel]-(>=bottom)-|",
options: [],
metrics: [
"top": textContainerInset.top,
"bottom": textContainerInset.bottom
],
views: [
"placeholderLabel": p
])
NSLayoutConstraint.activateConstraints(layoutConstraints)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment