NSLayoutConstraint.constraintsWithVisualFormat align bottom right - objective-c

I want to put a indicator view in a bottom right of container view, i have this code to insert view
var img:UIImageView?
img = UIImageView(frame: CGRect(x: 0, y: 0, width: singleCheckViewWidth, height: singleCheckViewHeight))
img!.image = UIImage(named: "check")
img!.tag = 21
img!.translatesAutoresizingMaskIntoConstraints = false
img!.backgroundColor = UIColor.redColor()
//Aggiungo la vista al fumetto
cell.textView!.addSubview(omg!)
The problem is that with this code i have icon in a top left with 10px margin and it works fine:
let iconVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-10-[indicator(\(singleCheckViewHeight))]",
options: [],
metrics: nil,
views: views)
allConstraints += iconVerticalConstraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-10-[indicator(\(singleCheckViewWidth))]",
options: [],
metrics: nil,
views: views)
allConstraints += horizontalConstraints
here is image:
but if i try to move image in a bottom left with this code:
let iconVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[indicator(\(singleCheckViewHeight))]-10-|",
options: [],
metrics: nil,
views: views)
allConstraints += iconVerticalConstraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[indicator(\(singleCheckViewWidth))]-10-|",
options: [],
metrics: nil,
views: views)
allConstraints += horizontalConstraints
i don't see the image anymore, if i try to put image in a top left with this code:
let iconVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-10-[indicator(\(singleCheckViewHeight))]",
options: [],
metrics: nil,
views: views)
allConstraints += iconVerticalConstraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[indicator(\(singleCheckViewWidth))]-10-|",
options: [],
metrics: nil,
views: views)
allConstraints += horizontalConstraints
I obtain image outside the container, like the image below:
Any ideas what's wrong? and how can i move the icon in a bottom right angle?
Thanks!

If all of the parent views haven't been aligned properly, nor the siblings, things could go Awry. On top of that,
cell.textView!.addSubview(omg!)
omg? I assume you meant img? Or am I wrong?
Also, on top of this, there's no mention as to what kind of container you're placing this in?
If it's just an NSView or UIView, then xyz.cell isn't the place to put it. If its a TableiewView, a cell could be, but are the constraints all set up. If its iOS, then is the UITableViewCell, the topmost view "of the cell" i.e., did you add a background view as an image view which could be overshadowing it?
Could you elaborate a little as to what the scenario is so we can get a better picture? (no pun intended)

Related

How to animate geometry using the primitiveRange property in SceneKit?

I am using Apple's SceneKit to render a tube which consists of 50 triangle strips as illustrated here:
I want to animate a "growing" tube by using the primitiveRange property.
let tube = createTube() // create's tube.geometry which has 50 elements
let tubeNode = SCNNode(geometry: tube.geometry)
...
let animation = CABasicAnimation(keyPath: "geometry.elements[0].primitiveRange")
animation.fromValue = NSValue(range: NSRange(location: 0, length: 0))
animation.toValue = NSValue(range: NSRange(location: 0, length: tube.geometry.elements.count))
animation.duration = 5
animation.repeatCount = Float.infinity
tubeNode.geometry?.addAnimation(animation, forKey: "don't care")
scene.rootNode.addChildNode(tubeNode)
Nothing is animating (I simply see the full tube above) and I am not getting any warnings on the console. If I change the key "geometry.elements.primitiveRange" to "foo" I do get the following warning on the console
ExtrudedTube[98737:24354579] [SceneKit] Error: _C3DModelPathResolverRegistryResolvePathWithClassName unknown path (
foo
)
Perhaps this property is not animatable? I don't see documentation that says it is or isn't. Any idea how to create the "growing tube" animation using this mesh in SceneKit?
I was never able to pull off the animation using the "keypath" (I think there probably is a way to do it, but there is no documentation on the details). I can use SCNAction though it it works well:
if let numPrimitives = tubeNode.geometry?.elements[0].primitiveCount {
tubeNode.geometry?.elements[0].primitiveRange = NSRange(location: 0, length: 0)
let duration : Double = 5.0
let growTube = SCNAction.customAction(duration: duration, action: {node, elapsedTime in
let f = Double(elapsedTime)/duration
let n = Int(f*Double(numPrimitives))
node.geometry?.elements[0].primitiveRange = NSRange(location: 0, length: n)
})
tubeNode.runAction(growTube)
}

Creating buttons with unique names through a for loop in Swift 4

Im building an app with a complex UI that requires 45 buttons. For a variety of reasons, I am not using Interface Builder. In order to update properties for specific buttons, I need each of the buttons to have a unique name, (Btn1, Btn2, Btn3...) Here is the code that I am using:
let buttonsArray = ["Btn1", "Btn2", "Btn3", "Btn4", "Btn5", "Btn6",
"Btn7", "Btn8", "Btn9", "Btn10", "Btn11", "Btn12",
"Btn13", "Btn14", "Btn15", "Btn16", "Btn17", "Btn18",
"Btn19", "Btn20", "Btn21", "Btn22", "Btn23", "Btn24",
"Btn25", "Btn26", "Btn27", "Btn28", "Btn29", "Btn30",
"Btn31", "Btn32", "Btn33", "Btn34", "Btn35", "Btn36"]
for button in buttonsArray {
let button = UIButton(frame: CGRect(x: nextx, y: nexty, width: btnsiz, height: btnsiz))
button.isUserInteractionEnabled = true
button.alpha = 0.05
button.tag = tagnum
tagnum += 1
button.backgroundColor = UIColor(red: 0.997, green: 0.645, blue: 0.014, alpha: 1.0)
button.setTitle(notesarray[count], for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
button.backgroundColor = UIColor(red: 0.991, green: 0.607, blue: 0.33, alpha: 1.0)
button.addTarget(self, action: #selector(btnPressed), for: .touchUpInside)
self.view.addSubview(button)
btnarray[count] = false
setNextX()
element += 1
count += 1
}
When a button is pressed it is recognized. I have assigned a unique tag number. I want to be able to update properties based upon the button name (Btn1) such as:
Btn1.isUserInteractionEnabled = true. I get the error message "Use of unresovled identifier 'Btn1'. How do I get the name specified as I could in Interface Builder with IBOutlet?
I'm afraid IBOutlets are an Interface Builder only thing - hence the 'IB' in the name 'IBOutlet'.
If you want to get a reference to a subview of view, you can use the UIView tag property. I see that you are already using this tag property, passing it 'tagnum', which looks like it increments for every button, similar to the names in the ButtonsArray.
For example, if you want to get the button with tag 1, you could request it like this:
let Btn1 = self.view.viewWithTag(1)
You could then do what you're suggesting:
Btn1.isUserInteractionEnabled = true
An aside, I would recommend you name your variables beginning with a lower case letter to follow best practices:
Follow case conventions. Names of types and protocols are
UpperCamelCase. Everything else is lowerCamelCase.

Adding extra information above the node in cytoscape.js

Using cytoscape.js to draw a graph. I need to add circle above the node at top-right position. After drawing the graph, is there any API wherein we can get positions of nodes.
Also, I have used the code as follows:
elements : {
nodes : [ {
data : {
id : '1',
name : 'A'
}
}
]
}
var pos = cy.nodes("#1").position();
'#1' is the ID of the node in the data attribute. However, we are not able to add the node/circle at that exact position.
If you want to get something like:
then this code adds the circle to a node knowing it's id:
function addCircle(nodeId, circleText){
var parentNode = cy.$('#' + nodeId);
if (parentNode.data('isCircle') || parentNode.data('circleId'))
return;
parentNode.lock();
var px = parentNode.position('x') + 10;
var py = parentNode.position('y') - 10;
var circleId = (cy.nodes().size() + 1).toString();
parentNode.data('circleId', circleId);
cy.add({
group: 'nodes',
data: { weight: 75, id: circleId, name: circleText, isCircle: true },
position: { x: px, y: py },
locked: true
}).css({
'background-color': 'yellow',
'shape': 'ellipse',
'background-opacity': 0.5
}).unselectify();
}
// ...
addCircle('1', 'Bubble A');
but it must be called after the node's positions are known, when the layout settles down.
The locking is there to prevent that node and it's circle get apart.
jsFiddle demo: http://jsfiddle.net/xmojmr/wvznb9pf/
Using compound node which would keep the node and it's circle together would be probably better, once the support for positioning child nodes is implemented.
Disclaimer: I'm cytoscape.js newbie, use at your own risk

merge two sprite nodes in sprite kit

I am designing a sprite kit game where I want to merge two sprite nodes (rect shapes) together and then act and move them as one sprite node ?
I've been searching lot and I didn't find results
Is that possible in sprite kit ? and how can I do it ?
I'll appreciate any help, Thanks
Add one node as a child of the other. If you set it's node2.physicsbody.dynamic=NO; it will move as a single node. There will be separate physicsbodies but you can set them to the same category bitmask.
The answer linked here may help with notation: How to detect contact on different areas of a physicsbody
If you have two sprite nodes, you simply do this :
[firstSprite addChild:secondSprite]
Here is an answer with which I have achieved what you are looking for using SpriteKit (Swift)
First apply Physics to your scene
Example:
self.physicsWorld.gravity = CGVectorMake(0, -9.8)
physicsWorld.contactDelegate = self
let sceneBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
sceneBody.friction = 1
self.physicsBody = sceneBody
self.physicsBody?.categoryBitMask = PhysicsCategory.Boarder
self.physicsBody?.contactTestBitMask = PhysicsCategory.None
self.physicsBody?.collisionBitMask = PhysicsCategory.Item
Second, Apply Physics to the two skspritenode's that you want to join together
Example
func mySpritetie1() {
spritetie1 = SKSpriteNode(imageNamed: "img1")
spritetie1.name = kAnimalNodeName
spritetie1.position = CGPoint(x: 170, y: 35)
spritetie1.size = CGSizeMake(36, 100)
spritetie1.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(22, 100))
spritetie1.physicsBody?.affectedByGravity = false
spritetie1.physicsBody?.categoryBitMask = PhysicsCategory.Item
spritetie1.physicsBody?.collisionBitMask = PhysicsCategory.Boarder
spritetie1.physicsBody?.contactTestBitMask = PhysicsCategory.Monster
self.addChild(spritetie1)
}
func mySpritetie2() {
spritetie2 = SKSpriteNode(imageNamed: "img2")
spritetie2.name = kAnimalNodeName
spritetie2.position = CGPoint(x: 250, y: 60)
spritetie2.size = CGSizeMake(90, 79)
spritetie2.physicsBody = SKPhysicsBody(circleOfRadius: 25)
spritetie2.physicsBody?.affectedByGravity = false
spritetie2.physicsBody?.categoryBitMask = PhysicsCategory.Item
spritetie2.physicsBody?.collisionBitMask = PhysicsCategory.Boarder
spritetie2.physicsBody?.contactTestBitMask = PhysicsCategory.Monster
self.addChild(spritetie2)
}
Third, now joining them
Example
let joint = SKPhysicsJointFixed.jointWithBodyA(spritetie1.physicsBody!, bodyB: spritetie2.physicsBody!,
anchor: CGPointMake(CGRectGetMidX(spritetie1.frame), CGRectGetMinY(spritetie2.frame)))
self.physicsWorld.addJoint(joint)
This will join the two body at the anchor point you give.
Now you can animate any one of that (spritetie1 or spritetie2) using SKAction and the other will animate as if they are one and the same joined at the anchor point you defined.
If you feel this answer helped please do approve it. Hope it will help someone out there.
Please use this two link to learn about all thats in my code:
https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Physics/Physics.html
A very basic and good tutorial to learn about simulating physics https://www.youtube.com/playlist?list=PLa41xEuH5n_pwuNm7Z3L5qxDhVE0sOEqb
Thanks

How to draw a triangle in a math graph?

How to draw a triangle in a math graph which displays X and Y axis.
To draw shapes using ActionScript2, you can use the moveTo() and lineTo() methods of the MovieClip object. You can specify line colour and thickness with lineStyle(), or make a solid shape using beginFill() and endFill().
So to draw your graph and triangle you could do the following steps:
Make a movieClip named "graph"
Define how big your graph should be (using the flash.geom.Rectangle object)
Draw a grey background using graph.beginFill(grey) and then moveTo() and lineTo()
Draw some blue lines at regular intervals for a grid
Draw the X and Y axes on the side and bottom of your grid
Make a second movieClip named "shape"
Pick 3 random points: moveTo(point1), lineTo(point2), lineTo(point3), lineTo(point1)
Here's how the code might look:
import flash.geom.Point;
import flash.geom.Rectangle;
function drawGraph(mc:MovieClip, rect:Rectangle):Void {
//this is a function to draw the graph
//draw the background
mc.beginFill(0xF8F8F8);
mc.moveTo(rect.left, rect.bottom);
mc.lineTo(rect.left, rect.top);
mc.lineTo(rect.right, rect.top);
mc.lineTo(rect.right, rect.bottom);
mc.lineTo(rect.left, rect.bottom);
mc.endFill();
//draw a grid
var unit:Number = 20;
mc.lineStyle(1, 0x0000FF, 20, true, "none", "round", "round");
var i:Number=rect.x;
do {
i=i+unit;
mc.moveTo(i, rect.bottom);
mc.lineTo(i, rect.top);
} while (i<rect.right);
i=rect.bottom;
do {
i=i-unit;
mc.moveTo(rect.left, i);
mc.lineTo(rect.right,i);
} while (i>rect.top);
//draw the axes
mc.lineStyle(2, 0x808080, 100, true, "none", "round", "round");
mc.moveTo(rect.left, rect.bottom);
mc.lineTo(rect.left, rect.top);
mc.moveTo(rect.left, rect.bottom);
mc.lineTo(rect.right, rect.bottom);
}
function randomPoint(rect:Rectangle):Point {
//this is a function which returns a random point within rect
var p:Point = new Point(rect.x+Math.random()*rect.width, rect.y+Math.random()*rect.height);
return p;
}
function drawTriangle(mc:MovieClip, rect:Rectangle):Void {
//this is a function to draw the triangle
// pick 3 random points within rect
var p1:Point = randomPoint(rect);
var p2:Point = randomPoint(rect);
var p3:Point = randomPoint(rect);
//connect the points to make a triangle
mc.lineStyle(3, 0xFF0000, 100, true, "none", "round", "round");
mc.moveTo(p1.x, p1.y);
mc.lineTo(p2.x, p2.y);
mc.lineTo(p3.x, p3.y);
mc.lineTo(p1.x, p1.y);
}
//make the 'graph' clip:
var myGraph:MovieClip = this.createEmptyMovieClip("myGraph", this.getNextHighestDepth());
//define the graph size:
var myRect:Rectangle = new Rectangle(50,50,300,300);
drawGraph(myGraph,myRect);//draw the graph
var myShape:MovieClip = this.createEmptyMovieClip("myShape", this.getNextHighestDepth());//make the 'shape' clip
drawTriangle(myShape,myRect);//draw a random triangle
//add a function to draw a new triangle when the graph is clicked:
myGraph.onRelease = function() {
myShape.clear();//erase the old triangle
drawTriangle(myShape,myRect);//draw a new one
}
You can click the graph to generate a new random triangle.
(source: webfactional.com)
It sounds like you need to know how the drawing API works in Flash. Your question is kind of vague, but this might help to get you started - google "Flash Drawing API" for more information.
var point1:Point = new Point (0, 0);
var point2:Point = new Point (25, -50);
var point3:Point = new Point (50, 0);
var s:Sprite = new Sprite();
s.graphics.lineStyle(1, 0xff0000);
s.graphics.beginFill(0x000000);
s.graphics.moveTo(point1.x, point1.y);
s.graphics.lineTo(point2.x, point2.y);
s.graphics.lineTo(point3.x, point3.y);
s.graphics.lineTo(point1.x, point1.y);
s.graphics.endFill();
s.graphics.lineStyle(0);
s.x = (stage.stageWidth - s.width) / 2;
s.y = ((stage.stageHeight - s.height) / 2) + 50;
addChild(s);
I hope that helps, let me know if you have any questions.
NOTE: This solution is using ActionScript 3. If you need AS2 this won't work, and off the top of my head I don't know how to help but you might just try googling "AS2 Drawing API" or something to that effect.