How to Focus last cell of visible cell of collection view? - objective-c

I want to focus and change the frame of last cell of visible cell of collectionView.
I want collection view behaviour like this.
I found the library that change the first cell of collection view but I want to change the frame of last cell. This library using flow layout.
override func prepareLayout() {
cache.removeAll(keepCapacity: false)
let standardHeight = UltravisualLayoutConstants.Cell.standardHeight
let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight
var frame = CGRectZero
var y: CGFloat = 0
for item in 0..<numberOfItems {
// 1
let indexPath = NSIndexPath(forItem: item, inSection: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
// 2
attributes.zIndex = item
var height = standardHeight
// 3
if indexPath.item == featuredItemIndex
{
// 4
let yOffset = standardHeight * nextItemPercentageOffset
y = collectionView!.contentOffset.y - yOffset
height = featuredHeight
} else if indexPath.item == (featuredItemIndex + 1) && indexPath.item != numberOfItems {
// 5
let maxY = y + standardHeight
height = standardHeight + max((featuredHeight - standardHeight) * nextItemPercentageOffset, 0)
y = maxY - height
}
// 6
frame = CGRect(x: 0, y: y, width: width, height: height)
//print("Item : \(item) : \(frame)");
attributes.frame = frame
cache.append(attributes)
y = CGRectGetMaxY(frame)
}
}
library uses above function to change the frame of all elements.
Can any one tell me that how can I achieve this.

You can use visible cells of a UICollectionView to get the array of visible cells and focus on the lastObject of the array

Related

displaying alert dialog in the correct location within a recyclerview

I'm making a custom button that when you long press on it a dialog will appear with a list of options to choose from.
The custom button works as it should, however, I'm having some trouble wrangling the dialog to show up exactly where I want it to.
this is the code that displays the dialog.
private void ShowReactionsDialog()
{
var context = Context;
var inflater = (LayoutInflater) context.GetSystemService(Context.LayoutInflaterService);
var dialogView = inflater.Inflate(Resource.Layout.react_dialog_layout, null);
var linearLayoutManager = new LinearLayoutManager(context)
{
Orientation = LinearLayoutManager.Horizontal
};
var adapter = new ReactionAdapter(_reactionList);
adapter.OnItemClicked += (sender, currentReaction) =>
{
UpdateReactButtonByReaction(currentReaction);
_reactAlertDialog.Cancel();
};
var rvReactions = dialogView.FindViewById<RecyclerView>(Resource.Id.reaction_rvReactions);
rvReactions.HasFixedSize = true;
rvReactions.SetLayoutManager(linearLayoutManager);
rvReactions.SetItemAnimator(new DefaultItemAnimator());
rvReactions.SetAdapter(adapter);
var dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.SetView(dialogView);
_reactAlertDialog = dialogBuilder.Create();
_reactAlertDialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
var window = _reactAlertDialog.Window;
window.SetBackgroundDrawableResource(Resource.Drawable.react_dialog_shape);
window.SetDimAmount(0);
// Setup dialog gravity and dynamic position
var windowManagerAttributes = window.Attributes;
windowManagerAttributes.Gravity = GravityFlags.AxisSpecified;
windowManagerAttributes.X = (int) GetX() + (Width / 2);
windowManagerAttributes.Y = (int) GetY() + (Height / 2);
_reactAlertDialog.Show();
var dialogWidth = GetIconSize() * _reactionList.Count;
if (dialogWidth > GetScreenMaxWidth())
{
dialogWidth = GetScreenMaxWidth();
}
window.SetLayout(dialogWidth, ViewGroup.LayoutParams.WrapContent);
}
I've tried messing with the gravity and the X & Y coordinates but it just wants to either go too high up or too low down, there's no consistent location it's sticking to. I want it to be above the button that's getting long tapped.
You can use the following code to make the AlertDialog show above the button.
int[] location = new int[2];
AndroidX.AppCompat.App.AlertDialog alertDialog = builder.Create();
Window window = alertDialog.Window;
WindowManagerLayoutParams attributes = window.Attributes;
//Get the location of the button and location[0] is X and location[1] is Y
button.GetLocationInWindow(location);
//Set the height of the AlertDialog
int height = 400;
int a = button.Height / 2;
int c = location[1];
//Get the distance of top
attributes.Y = c - a - height;
window.Attributes = attributes;
//Set the AlertDialog location according to the distance of top
window.SetGravity(GravityFlags.Top);
alertDialog.Show();
//Set the Width and Hight of the AlertDialog
alertDialog.Window.SetLayout(800, height);

How to override the parent layout/view opacity for certain elements in xamarin forms?

So I'm trying to develop a custom control which has Opacity of about 0.2, and its an entry, but the problem here is if I set the Opacity of the entry, then the Placeholder or the hint text also gets the opacity, and my custom control has an image as well, which gets the opacity as well, is there a way to override this?
I tried setting the alpha in the renderer but that doesn't seem to do the trick,
Here's my renderer and the output I need, but what I'm getting in actual
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || e.NewElement == null)
return;
var element = (ImageEntry)this.Element;
this.Control.Placeholder = element.Placeholder;
var textField = this.Control;
if (!string.IsNullOrEmpty(element.Image))
{
switch (element.ImageAlignment)
{
case ImageAlignment.Left:
textField.LeftViewMode = UITextFieldViewMode.Always;
textField.LeftView = GetImageView(element.Image, element.ImageHeight, element.ImageWidth);
break;
case ImageAlignment.Right:
textField.RightViewMode = UITextFieldViewMode.Always;
textField.RightView = GetImageView(element.Image, element.ImageHeight, element.ImageWidth);
break;
}
}
this.Control.Layer.CornerRadius = 25;
textField.BorderStyle = UITextBorderStyle.None;
textField.Alpha = 1;
CALayer bottomBorder = new CALayer
{
Frame = new CGRect(0.0f, element.HeightRequest - 1, this.Frame.Width, 1.0f),
BorderWidth = 2.0f,
BorderColor = element.LineColor.ToCGColor()
};
textField.Layer.AddSublayer(bottomBorder);
textField.Layer.MasksToBounds = true;
}
but this is what I'm getting

Bouncing ball slightly leaves the screen frame in Spritekit [duplicate]

I've been racking my brain and searching here and all over to try to find out how to generate a random position on screen to spawn a circle. I'm hoping someone here can help me because I'm completely stumped. Basically, I'm trying to create a shape that always spawns in a random spot on screen when the user touches.
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenHeight = screenSize.height
let screenWidth = screenSize.width
let currentBall = SKShapeNode(circleOfRadius: 100)
currentBall.position = CGPointMake(CGFloat(arc4random_uniform(UInt32(Float(screenWidth)))), CGFloat(arc4random_uniform(UInt32(Float(screenHeight)))))
self.removeAllChildren()
self.addChild(currentBall)
}
If you all need more of my code, there really isn't any more. But thank you for whatever help you can give! (Just to reiterate, this code kind of works... But a majority of the spawned balls seem to spawn offscreen)
The problem there is that you scene is bigger than your screen bounds
let viewMidX = view!.bounds.midX
let viewMidY = view!.bounds.midY
print(viewMidX)
print(viewMidY)
let sceneHeight = view!.scene!.frame.height
let sceneWidth = view!.scene!.frame.width
print(sceneWidth)
print(sceneHeight)
let currentBall = SKShapeNode(circleOfRadius: 100)
currentBall.fillColor = .green
let x = view!.scene!.frame.midX - viewMidX + CGFloat(arc4random_uniform(UInt32(viewMidX*2)))
let y = view!.scene!.frame.midY - viewMidY + CGFloat(arc4random_uniform(UInt32(viewMidY*2)))
print(x)
print(y)
currentBall.position = CGPoint(x: x, y: y)
view?.scene?.addChild(currentBall)
self.removeAllChildren()
self.addChild(currentBall)
First: Determine the area that will be valid. It might not be the frame of the superview because perhaps the ball (let's call it ballView) might be cut off. The area will likely be (in pseudocode):
CGSize( Width of the superview - width of ballView , Height of the superview - height of ballView)
Once you have a view of that size, just place it on screen with the origin 0, 0.
Secondly: Now you have a range of valid coordinates. Just use a random function (like the one you are using) to select one of them.
Create a swift file with the following:
extension Int
{
static func random(range: Range<Int>) -> Int
{
var offset = 0
if range.startIndex < 0 // allow negative ranges
{
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
And now you can specify a random number as follows:
Int.random(1...1000) //generate a random number integer somewhere from 1 to 1000.
You can generate the values for the x and y coordinates now using this function.
Given the following random generators:
public extension CGFloat {
public static var random: CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) }
public static func random(between x: CGFloat, and y: CGFloat) -> CGFloat {
let (start, end) = x < y ? (x, y) : (y, x)
return start + CGFloat.random * (end - start)
}
}
public extension CGRect {
public var randomPoint: CGPoint {
var point = CGPoint()
point.x = CGFloat.random(between: origin.x, and: origin.x + width)
point.y = CGFloat.random(between: origin.y, and: origin.y + height)
return point
}
}
You can paste the following into a playground:
import XCPlayground
import SpriteKit
let view = SKView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
XCPShowView("game", view)
let scene = SKScene(size: view.frame.size)
view.presentScene(scene)
let wait = SKAction.waitForDuration(0.5)
let popIn = SKAction.scaleTo(1, duration: 0.25)
let popOut = SKAction.scaleTo(0, duration: 0.25)
let remove = SKAction.removeFromParent()
let popInAndOut = SKAction.sequence([popIn, wait, popOut, remove])
let addBall = SKAction.runBlock { [unowned scene] in
let ballRadius: CGFloat = 25
let ball = SKShapeNode(circleOfRadius: ballRadius)
var popInArea = scene.frame
popInArea.inset(dx: ballRadius, dy: ballRadius)
ball.position = popInArea.randomPoint
ball.xScale = 0
ball.yScale = 0
ball.runAction(popInAndOut)
scene.addChild(ball)
}
scene.runAction(SKAction.repeatActionForever(SKAction.sequence([addBall, wait])))
(Just make sure to also paste in the random generators, too, or to copy them to the playground's Sources, as well as to open the assistant editor so you can see the animation.)

createjs Y position inside of movieclip

I have a graphic in an animation playing within a movieclip
What I want to do is get the x and y position of the graphic inside of that movieclip as it animates.
but I'm finding that the x an y don't update, even though at the moment, I'm checking within the tick function, I'm using globalToLocal
function tickHandler(event) {
//get the x and y of this mc using globalToLocal
console.log(exportRoot.game_anim.meterMC.awd.globalToLocal(exportRoot.game_anim.meterMC.awd.x, exportRoot.game_anim.meterMC.awd.y))
stage.update();
}
exportRoot.gotoAndStop("game")
exportRoot.game_anim.meterMC.arrowYou.addEventListener("mousedown",function (evt) {
var _this = evt.target
var mouseRight = 0;
var mouseLeft = 180;
var offset = {x: _this.x - evt.stageX, y: _this.y - evt.stageY};
evt.addEventListener("mousemove" , function(ev){
// )
var pt = exportRoot.game_anim.meterMC.globalToLocal(stage.mouseX, stage.mouseY)
if ( pt.y > mouseLeft){
percent = 100;
} else if (pt.y < mouseRight){
percent = 0;
} else {
percent = Math.round(((pt.y - mouseRight) / (mouseLeft - mouseRight)*100));
_this.y = pt.y;
}
if ( pt.y > mouseLeft){
}
;
})
});
Try using localToGlobal with a static point in your target clip. For example:
var pt = myMC.subMC.localToGlobal(0,0);
console.log(pt.x, pt.y);

Centre Buttons In Swift - Objective C Conversion Issue

In Objective C, I am using a function to centre some buttons, which works fine.
The buttons centre perfectly on the screen.
However, converting the code to swift it isn't working as expected. There is extra space on the left hand side:
func centerImageViews()
// Measure the total width taken by the buttons
var width:CGFloat = 0.0
for (index, item) in enumerate(self.soundBoxes) {
if(item.tag>=numberOfBoxes){
item.alpha=0
}else{
item.alpha=1
width += item.bounds.size.width + 10
}
if (width > 10){
width -= 10;
}
// If the buttons width is shorter than the visible bounds, adjust origin
var origin:CGFloat = 0;
if (width < self.view.frame.size.width){
origin = (self.view.frame.size.width - width) / 2.0;
}
// Place buttons
var x:CGFloat = origin;
var y:CGFloat = 200;
for (index, item) in enumerate(self.soundBoxes) {
item.center = CGPointMake(x + item.bounds.size.width/2.0, y + item.bounds.size.height/2.0);
x += item.bounds.size.width + 10;
}
}
}
In Objective C:
- (void)centerImageViews:(NSArray*)imageViews withCount:(int)number
{
int kButtonSeperator=10;
// Measure The Total Width Of Our Buttons
CGFloat width = 0;
for (UIImageView* hit in soundBoxes)
if (hit.tag>=numberOfBoxes) {
hit.alpha=0;
} else {
width += hit.bounds.size.width + kButtonSeperator;
hit.alpha=1;
}
if (width > kButtonSeperator)
width -= kButtonSeperator;
CGFloat origin = 0;
if (width < self.view.frame.size.width)
origin = (self.view.frame.size.width - width) / 2.f;
CGFloat x = origin;
CGFloat y = 85;
UIImageView* hit;
for (hit in imageViews) {
hit.center = CGPointMake(x + hit.bounds.size.width/2.f, y + hit.bounds.size.height/2.f);
//NSLog(#"X Is %f",hit.center.x);
x += hit.bounds.size.width + kButtonSeperator;
}
}
}