Swift - UIPanRecognizer in a UIStackView - user-interface

I want to make a UIPanRecognizer in a UIStackView. The UI looks like this.
There's a big square which is a StackView which contains 9 labels.
My goal is when I start to drag my finger within the StackView and if a label contains that touchpoint then its color should be blue and on and on. If I lift my finger all of the labels background color turn back to white.
The labels are in a OutletCollection.
Here's my code:
#IBOutlet var testLabels: [UILabel]!
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
var touchedPoint: CGPoint!
if let view = recognizer.view{
if recognizer.state == .began || recognizer.state == .changed {
touchedPoint = recognizer.location(in: view)
for index in testLabels.indices {
if testLabels[index].frame.contains(touchedPoint) {
testLabels[index].backgroundColor = UIColor.blue
}
}
}
if recognizer.state == .ended {
for index in testLabels.indices {
testLabels[index].backgroundColor = UIColor.white
}
}
}
Right now when I touch for example the top-left square and start to drag my finger to the right the whole first column turns blue then the second then the third. That happens when I touch any labels of the first row, but nothing happens when I touch the other squares.
First time, I tried to solve my problem by handle the squares just as an OutletCollection (without the StackView) and the recognizer just worked fine! The reason why I experiment with the StackView that it's so easier to make the layout(just a few constraints needed, without the StackView it is a nightmare).
I'd appreciate any help. Thank you.
Edit: probably this one helps?
Access nested stack views

Each label is a subview of its containing stack view (which is also probably a subview of a stack view), and each label has its own coordinate space.
Assuming your UIPanGestureRecognizer is assigned to the view controller's view, you need to translate the coordinates / frames.
This should work for you:
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
var touchedPoint: CGPoint!
if let view = recognizer.view{
if recognizer.state == .began || recognizer.state == .changed {
touchedPoint = recognizer.location(in: view)
for index in testLabels.indices {
// translate / convert the label's bounds from its frame to the view's coordinate space
let testFrame = view.convert(testLabels[index].bounds, from:testLabels[index] )
// check the resulting testFrame for the point
if testFrame.contains(touchedPoint) {
testLabels[index].backgroundColor = UIColor.blue
}
}
}
else if recognizer.state == .ended {
for index in testLabels.indices {
testLabels[index].backgroundColor = UIColor.white
}
}
}
}
You can also simplify your code a bit by using for object in collection instead of indices. This is functionally the same as above, but maybe a little simpler:
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
var touchedPoint: CGPoint!
if let view = recognizer.view{
if recognizer.state == .began || recognizer.state == .changed {
touchedPoint = recognizer.location(in: view)
for lbl in testLabels {
// translate / convert the label's bounds from its frame to the view's coordinate space
let testFrame = view.convert(lbl.bounds, from:lbl )
// check the resulting testFrame for the point
if testFrame.contains(touchedPoint) {
lbl.backgroundColor = .blue
}
}
}
else if recognizer.state == .ended {
for lbl in testLabels {
lbl.backgroundColor = .white
}
}
}
}

Related

How can SwiftUI animations be isolated to child views?

I'm trying to animate a transformation within a cell of a grid view, but I don't want this animation to affect the layout of the cells as they are repositioned by data changes. I feel like this should be simple to do, but it doesn't work no matter what I try.
Perhaps someone can demonstrate SwiftUI where cells in a grid view can reorder themselves without a spring animation while the cells use a spring animation to resize locally? That would be greatly appreciated!
var body: some View {
LazyVGrid(columns) {
ForEach(dataSource.dataList) { // This is an array of structs
CellView(data: $0)
}
}
.animation(.default)
}
struct CellView: View {
let data: CellData
#State var contentScale: CGFloat = 1
init(data: CellData) {
self.data = data
let anim = Animation.interpolatingSpring(stiffness: 50, damping: 5)
withAnimation(anim) {
self.contentScale = calcScaleFrom(data: data)
}
}
var body: some View {
// Configure cell with data
// and animate scale based on data properties
}
}
Ok, I didn't find the answer to my exact question... but I did find a workaround. My precise aim was making my cells update their content with a spring animation, but making the grid reorder the cell with the default animation. To do this I simply added a withAnimation block in my grid's data model code which selects the style of animation based on whether the data list changed order!
#Published var currentList: [CellData]
func updateData() {
let newList = ...
let anim: Animation
if newList.map({$0.id}).elementsEqual(currentList.map({$0.id})) {
// Data may have changed but does not require any cell reordering
anim = Animation.interpolatingSpring(stiffness: 80, damping: 5)
} else {
// Cells will change order!
anim = .default
}
withAnimation(anim) {
currentList = newList
}
}

iOS Autolayout: Oddly expand-animation of UITextView inside an UIScrollView

I'm trying to animate the height constraint of a UITextView inside a UIScrollView. When the user taps the "toggle" button, the text should appear in animation from top to bottom. But somehow UIKit fades in the complete view.
To ensure the "dynamic" height depending on the intrinsic content-size, I deactivate the height constraint set to zero.
#IBAction func toggle() {
layoutIfNeeded()
UIView.animate(withDuration: 0.6, animations: { [weak self] in
guard let self = self else {
return
}
if self.expanded {
NSLayoutConstraint.activate([self.height].compactMap { $0 })
} else {
NSLayoutConstraint.deactivate([self.height].compactMap { $0 })
}
self.layoutIfNeeded()
})
expanded.toggle()
}
The full code of this example is available on my GitHub Repo: ScrollAnimationExample
Reviewing your GitHub repo...
The issue is due to the view that is animated. You want to run .animate() on the "top-most" view in the hierarchy.
To do this, you can either create a new property of your ExpandableView, such as:
var topMostView: UIView?
and then set that property from your view controller, or...
To keep your class encapsulated, let it find the top-most view. Replace your toggle() func with:
#IBAction func toggle() {
// we need to run .animate() on the "top" superview
// make sure we have a superview
guard self.superview != nil else {
return
}
// find the top-most superview
var mv: UIView = self
while let s = mv.superview {
mv = s
}
// UITextView has subviews, one of which is a _UITextContainerView,
// which also has a _UITextCanvasView subview.
// If scrolling is disabled, and the TextView's height is animated to Zero,
// the CanvasView's height is instantly set to Zero -- so it disappears instead of animating.
// So, when the view is "expanded" we need to first enable scrolling,
// and then animate the height (to Zero)
// When the view is NOT expanded, we first disable scrolling
// and then animate the height (to its intrinsic content height)
if expanded {
textView.isScrollEnabled = true
NSLayoutConstraint.activate([height].compactMap { $0 })
} else {
textView.isScrollEnabled = false
NSLayoutConstraint.deactivate([height].compactMap { $0 })
}
UIView.animate(withDuration: 0.6, animations: {
mv.layoutIfNeeded()
})
expanded.toggle()
}

UIView height constraint animation, which has anchor connection with other views

Xcode swift 4
I have some views that are added dynamically in code one below another.
Each new view top anchor is connected to previous view bottom anchor.
And each view have a button that make view to expand/collapse with animation. Here is button code :
let fullHeight : CGFloat = 240
let smallHeight : CGFloat = 44
let currentHeigth = rootView.frame.size.height //I use this to get current height and understand expanded view or not
let heighCons = rootView.constraints.filter //I use this to deactivate current height Anchor constraint
{
$0.firstAttribute == NSLayoutAttribute.height
}
NSLayoutConstraint.deactivate(heighCons)
rootView.layoutIfNeeded()
if currentHeigth == smallHeight
{
rootView.heightAnchor.constraint(equalToConstant: fullHeight).isActive = true
rootView.setNeedsLayout()
UIView.animate(withDuration: 0.5)
{
rootView.layoutIfNeeded() //animation itself
}
}
else
{
rootView.heightAnchor.constraint(equalToConstant: smallHeight).isActive = true
rootView.setNeedsLayout()
UIView.animate(withDuration: 0.5)
{
rootView.layoutIfNeeded() //animation itself
}
}
This all works perfectly but i have a problem : view that below current expanding view changes it y position immediately with no animation. Its just jumping to previous view bottom anchor, that would be active after animation finish.
So my question is :
1) what is the right way to make height constraint animation, when views are connected to each other by bottom/top animation?
2) my goal is just to make a view that would expand/collapse on button click, maybe i should do it another way?
Here's an approach using Visiblity Gone Extension
extension UIView {
func visiblity(gone: Bool, dimension: CGFloat = 0.0, attribute: NSLayoutAttribute = .height) -> Void {
if let constraint = (self.constraints.filter{$0.firstAttribute == attribute}.first) {
constraint.constant = gone ? 0.0 : dimension
self.layoutIfNeeded()
self.isHidden = gone
}
}
}
Usage
expanview.visiblity(gone: true,dimension: 0)
Example
#IBOutlet weak var msgLabel: UILabel!
#IBOutlet weak var expanview: UIView!
#IBAction func toggleCollapisbleView(_ sender: UIButton) {
if sender.isSelected{
sender.isSelected = false
expanview.visiblity(gone: false,dimension: 128)
sender.setTitle("Collapse",for: .normal)
}
else{
sender.isSelected = true
expanview.visiblity(gone: true,dimension: 0)
sender.setTitle("Expand",for: .normal)
msgLabel.text = "Visiblity gone"
}
}

Set color of NSButton programmatically swift

I generate some NSButtons programmatically with this code:
for i in 1...height {
for j in 1...width {
var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
but.tag = k
but.title = ""
but.action = Selector("buttonPressed:")
but.target = self
but.bezelStyle = NSBezelStyle(rawValue: 6)!
but.layer?.backgroundColor = NSColor.blackColor().CGColor
var ges = NSClickGestureRecognizer(target: self, action: Selector("addFlag:"))
ges.buttonMask = 0x2
ges.numberOfClicksRequired = 1
but.addGestureRecognizer(ges)
ar.append(but)
self.view.addSubview(but)
x += 30
k++
}
y += 30
x = 0
}
And I need to set the background color of all buttons to gray or black (randomly). I have no idea how to get or set the NSButton background color. I'm quite new to swift programming and I don't really know obj-c, so if you'll write it on swift, I'll really appreciate it!
I'm doing it with this code
final class MyButton: NSButton {
override func awakeFromNib() {
let layer = CALayer()
layer.backgroundColor = CGColorCreateGenericRGB(59.0/255, 52.0/255.0, 152.0/255.0, 1.0)
self.wantsLayer = true
self.layer = layer
}
}
I read throgh the NSButton reference guide, And it seems that the only way to change it it changing the image. But I have gotten a way to create an image using a colour. Add this extionsion at the top of your class file
extension NSImage {
class func swatchWithColor(color: NSColor, size: NSSize) -> NSImage {
let image = NSImage(size: size)
image.lockFocus()
color.drawSwatchInRect(NSMakeRect(0, 0, size.width, size.height))
image.unlockFocus()
return image
}
}
This will allow us to later create NSImage's using a UIColour. Lastly, When you want to create your button, Set the image using the extension we made.
myButton.image = NSImage.swatchWithColor( NSColor.blackColor(), size: NSMakeSize(100, 100) )
For the size parameter set it to your button's size.
UPDATE* If you want to randomly choose the colour you can do this..
var randomIndex = arc4random_uniform(2) + 1 //Creates a random number between 1 and 2
var colour = NSColor() //Empty colour
if randomIndex == 1 {
//If the random number is one then the colour is black
colour = NSColor.blackColor()
}
else {
//Else if it's not one it's grey
colour = NSColor.grayColor()
}
//set the button's image to the new colour
myButton.image = NSImage.swatchWithColor(colour, size: //My button size)
To get the size go to your storyboard, click on your button and go to the ruler tab. There it shows your button's size.
The bad news is that there is, IMHO, no good way of colouring buttons; they all have advantages and drawbacks.
For everyone who, like me, felt curious about colouring buttons under Yosemite I have written what may not be the ultimate guide to colouring buttons, but definitely a strong contender:
http://www.extelligentcocoa.org/colouring-buttons/
This covers all styles of buttons, and has screenshots for almost any combination, using
backgroundColor
drawRect
cell backgroundColor
monochrome layerEffect
whiteBalance Adjust layerEffect
images set in IB
subclassing NSButton and adding images depending on the button state
If anyone can think of another way of colouring buttons, I'm interested to hear of it!
Okay, here is what I did when I needed to change the look of a button: subclass it.
//
// LSButtonColor.swift
//
// Created by Lloyd Sargent on 8/26/16.
// Copyright © 2016 Canna Software. All rights reserved.
// License: 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 Cocoa
class LSButtonColor: NSButton {
fileprivate struct AssociatedKeys {
static var variableDictionary = "ls_variableDictionary"
}
fileprivate var variableDictionary: [String:AnyObject]! {
get {
var localVariableDictionary = objc_getAssociatedObject(self, &AssociatedKeys.variableDictionary) as! [String:AnyObject]!
if localVariableDictionary == nil {
localVariableDictionary = [String:AnyObject]()
objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, localVariableDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return localVariableDictionary
}
set(updatedDictionary) {
objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, updatedDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var backgroundColor: NSColor! {
get {
return variableDictionary["backgroundColor"] as? NSColor
}
set(newBackgroundColor) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["backgroundColor"] = newBackgroundColor
variableDictionary = localVariableDictionary
}
}
var altBackgroundColor: NSColor! {
get {
return variableDictionary["altBackgroundColor"] as? NSColor
}
set(newAltBackgroundColor) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["altBackgroundColor"] = newAltBackgroundColor
variableDictionary = localVariableDictionary
}
}
var borderColor: NSColor! {
get {
return variableDictionary["borderColor"] as? NSColor
}
set(newBorderColor) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["borderColor"] = newBorderColor
variableDictionary = localVariableDictionary
self.layer?.borderColor = newBorderColor.cgColor
}
}
var cornerRadius: CGFloat {
get {
return variableDictionary["cornerRadius"] as! CGFloat
}
set(newCornerRadius) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["cornerRadius"] = newCornerRadius as AnyObject?
variableDictionary = localVariableDictionary
self.layer?.cornerRadius = newCornerRadius
}
}
var borderWidth: CGFloat {
get {
return variableDictionary["borderWidth"] as! CGFloat
}
set(newBorderWidth) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["borderWidth"] = newBorderWidth as AnyObject?
variableDictionary = localVariableDictionary
self.layer?.borderWidth = newBorderWidth
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
if self.isHighlighted {
if self.layer != nil {
self.layer?.backgroundColor = self.altBackgroundColor.cgColor
}
}
else {
if self.layer != nil {
self.layer?.backgroundColor = self.backgroundColor.cgColor
}
}
}
}
Okay, the first thing you might be puzzling over is the objc_getAssociatedObject - originally I did this as a category and it is an easy-peasy way of adding variables to categorys (everyone says you can’t do it, but everyone doesn’t realize that, yes, you can - it’s just not obvious).
Unfortunately, I ran into some issues, so I just made it a class - and didn’t bother to take out the associated object (why mess with success?)
Anyway, you should be able to pull out the relevant code to change the background of any button.

How does one manually tell NSTextContainer to recalculate the lineFragmentRects?

In my application, I have been adding support for NSTextView allowing subviews to work naturally with the text editor. (For example, pressing "enter" drops every subview lower than the insertion point, and text wraps around subviews.)
I have successfully been able to get word wrap around subviews by overridinglineFragmentRectForProposedRect(proposedRect: NSRect,
sweepDirection: NSLineSweepDirection,
movementDirection: NSLineMovementDirection,
remainingRect: NSRectPointer) -> NSRect.
However, when a subview is dragged, or resized, the breaks in the text need to be recalculated to get the desired effect. The text needs to update itself to wrap around the subview as it is dragged or resized. However, I noticed that typing on a line updates the lineFragmentRect for that line. Is there a way to immediately mark the text as "dirty" after the subview is dragged? Here is the code for the text container subclass:
import Cocoa
class CASTextContainer: NSTextContainer {
var mainView: CASTextView = CASTextView()
var textSubviews: Array<AnyObject> {
get {
return mainView.subviews
}
}
override var simpleRectangularTextContainer: Bool {
get {
return false
}
}
func rectForActiveRange() -> NSRect {
let range = layoutManager.glyphRangeForCharacterRange(textView.selectedRange, actualCharacterRange:nil)
var rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: self)
rect = NSOffsetRect(rect, textView.textContainerOrigin.x, textView.textContainerOrigin.y)
return rect;
}
override func lineFragmentRectForProposedRect(proposedRect: NSRect,
sweepDirection: NSLineSweepDirection,
movementDirection: NSLineMovementDirection,
remainingRect: NSRectPointer) -> NSRect
{
remainingRect.initialize(NSZeroRect)
var frames: Array<NSRect> = []
if textSubviews.isEmpty {
let fullRect = NSMakeRect(0, 0, containerSize.width, containerSize.height)
return NSIntersectionRect(fullRect, proposedRect)
}
for view in textSubviews {
frames.append(view.frame)
}
// Sort the array so that the frames are ordered by increasing origin x coordinate.
let fullRect = NSMakeRect(0, 0, containerSize.width, containerSize.height)
let region = NSIntersectionRect(fullRect, proposedRect)
let sortedFrames: Array<NSRect> = sorted(frames, { (first: NSRect, second: NSRect) -> Bool in
return first.origin.x < second.origin.x
})
// Get the first rectangle height that overlaps with the text region's height.
var textDrawingRegion = NSZeroRect
var subviewFrame = NSZeroRect // Will be needed later to set remainingRect pointer.
var precedingRegion: NSRect = NSZeroRect // Hold the view frame preceding our insertion point.
for frame in sortedFrames {
if region.origin.y + NSHeight(region) >= frame.origin.y &&
region.origin.y <= frame.origin.y + NSHeight(frame)
{
if region.origin.x <= frame.origin.x {
// Calculate the distance between the preceding subview and the approaching one.
var width: CGFloat = frame.origin.x - precedingRegion.origin.x - NSWidth(precedingRegion)
textDrawingRegion.origin = region.origin
textDrawingRegion.size = NSMakeSize(width, NSHeight(region))
subviewFrame = frame
break
}
else {
precedingRegion = frame
}
}
}
if textDrawingRegion == NSZeroRect {
return region
}
else {
// Set the "break" in the text to the subview's location:
let nextRect = NSMakeRect(subviewFrame.origin.x + NSWidth(subviewFrame),
region.origin.y,
NSWidth(proposedRect),
NSHeight(proposedRect))
remainingRect.initialize(nextRect)
return textDrawingRegion
}
}
}

Resources