Can I put a static image in a UIButton.imageView? that is animating? - swift

I have a custom UIButton (MovesButton) with an image that I don't want to change or remove. But when I set button.imageView?.animationImages with bunch of images and start animating it, it removes my button's initial photo I have. If I have the static photo as a background, it looks like it is on fire. I want the fire to be as a background and preferably in the same UIButton class.
private func putAnimation(button: MovesButton) {
var images: [UIImage] = []
if button.animation == ButtonAnimations.None {
print("None11")
return
} else if button.animation == ButtonAnimations.SmallFire {
for i in 0 ... ButtonAnimations.SmallFire.1 {
images.append(UIImage(named: "\(ButtonAnimations.SmallFire.0)\(i)")!) //ButtonAnimations.SmallFire.0 = "smallFire"
}
} else if button.animation == ButtonAnimations.BigFire {
for i in 0 ... ButtonAnimations.BigFire.1 {
images.append(UIImage(named: "\(ButtonAnimations.BigFire.0)\(i)")!)
}
} else { print("weird button animations") }
button.imageView?.animationImages = images
button.imageView?.animationDuration = 1
button.imageView?.startAnimating()
}
I don't want to use a hacky trick of putting an imageView or another button behind MovesButton
I want the same animation result as a button.imageView.animationImages but as the backgroundImage. Is this possible?

Instead of image view animation, use image animation. Call UIImage animatedImage(with:duration:) to form an animated image. Set that as your button’s background image and you’re all set.

Related

Touch Gesture Recognizer to clear screen of random function

I am building a collage in Xcode with a set background image and a random int function to display an image.
I tried using a tapGestureRecognizer to 1) display the random image and 2) clear the screen after using self.clearScreen. The images are displaying but they do not disappear when the next image is displayed.
import UIKit
import C4
class WorkSpace: CanvasController {
override func setup() {
var myRandomNumber: Int?
//Background Image
let background = Image("background")
background?.constrainsProportions = true
background?.width = self.canvas.width
background?.height = self.canvas.height
self.canvas.add(background)
canvas.addTapGestureRecognizer { (locations, center, state) in
self.clearScreen
myRandomNumber = random(below: 4)
}
}
if myRandomNumber == 1 {
let tree = Image("Tree")
tree?.constrainsProportions = true
tree?.width = self.canvas.width
tree?.origin = Point(0.0, self.canvas.height/2.0)
self.canvas.add(tree)
print("number1")
}
if myRandomNumber == 2 {
let boy = Image("boy")
boy?.constrainsProportions = true
boy?.width = self.canvas.width
boy?.origin = Point(0.0, self.canvas.height/2.0)
self.canvas.add(boy)
}
if myRandomNumber == 3 {
let woman = Image("woman")
woman?.constrainsProportions = true
woman?.width = self.canvas.width
woman?.height = self.canvas.height
self.canvas.add(woman)
}
}
}
I would like the screen to clear the pictures and replace with another.
func clearScreen() {
for view in self.view.subView {
view.removeFromSuperView()
}
}
After looking at the C4 pod docs:
Check the view hierarchy after adding to canvas
/// Adds a view to the end of the receiver’s list of subviews.
/// When working with C4, use this method to add views because it handles the addition of both UIView and View.
public func add<T>(_ subview: T?) {...}
And then try removing subviews with their supplied methods:
/// Unlinks the view from the receiver and its window, and removes it from the responder chain.
/// Calling this method removes any constraints that refer to the view you are removing, or that refer to any view in the
/// subtree of the view you are removing.
/// When working with C4, use this method to add views because it handles the removal of both UIView and View.
/// ````
/// let v = View(frame: Rect(0,0,100,100))
/// let subv = View(frame: Rect(25,25,50,50))
/// v.add(subv)
/// v.remove(subv)
/// ````
/// - parameter subview: The view to be removed.
public func remove<T>(_ subview: T?) {
if let v = subview as? UIView {
v.removeFromSuperview()
} else if let v = subview as? View {
v.view.removeFromSuperview()
} else {
fatalError("Can't remove subview of class `\(type(of: subview))`")
}
}

What control to use to capture image from camera and show on ui as thumbnail with events xamarin ios

I have created a view like this in my xamarin iOS mobile project.
User will be able to click on the capture images button to take a picture and set the image property of the image view. I would like to know how can i allow the user longpress a image (after it has been captured) and popup a message box to delete the image.
I have tried what Sameer has suggested in his comment like so in my ViewDidLoad
var gestureRecognizer = new UILongPressGestureRecognizer();
gestureRecognizer.AddTarget(() => ButtonLongPressed(gestureRecognizer));
img1.AddGestureRecognizer(gestureRecognizer);
img2.AddGestureRecognizer(gestureRecognizer);
When i click and hold on the image nothing happens. I have added these image views via the designer.
After a little more research and using the comment from #Junior Jiang - MSFT. I have made a bit progress but i would like to know which UIImage view has been clicked.
Heres my current code:
public JobImagesViewController(Job passedInCurrentJob) : base("JobImagesViewController", null)
{
currentJob = passedInCurrentJob;
uIImageViews = new List<UIImageView>();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
uIImageViews.Add(img1);
uIImageViews.Add(img2);
uIImageViews.Add(img3);
uIImageViews.Add(img4);
uIImageViews.Add(img5);
uIImageViews.Add(img6);
uIImageViews.Add(img7);
uIImageViews.Add(img8);
uIImageViews.Add(img9);
uIImageViews.Add(img10);
InitialiseImageGrid();
// Add a Save button to the navigation bar
this.NavigationItem.SetRightBarButtonItem(
new UIBarButtonItem("Save", UIBarButtonItemStyle.Done, (sender, args) =>
{
//TODO if else block with all logic to check if there are images etc.
//TODO prompt user and ask if they would like to save images.
UIAlertView alert = new UIAlertView("Save Images?", "Save images against the Job?", null, "Yes", new string[] { "No" });
alert.Clicked += (s, e) =>
{
if (e.ButtonIndex == 0) // Yes clicked
{
SaveJobImages();
}
};
alert.Show();
}), true);
}
[Export("ImageLongPressed:")]
public void ImageLongPressed(UILongPressGestureRecognizer gestureRecognizer)
{
if (gestureRecognizer.State != UIGestureRecognizerState.Began)
{
return;
// Needed because selector is executed twice, because Long-press gestures are continuous
}
// Perform action of opening the dialog to select/take a picture, replacing the ? image with the new image
UIAlertView alert = new UIAlertView("Delete this image ?" , "Are you sure you want to delete this image?", null, "Yes", new string[] { "No" });
alert.Clicked += (s, e) =>
{
if (e.ButtonIndex == 0) // 'Accept' clicked
{
// TODO how to get the image which has been clicked??
}
};
alert.Show();
}
private void InitialiseImageGrid()
{
_imageList = DataAccess.GetImages(currentJob.jobAddressID);
var imageBytes = _imageList.Select(x => x.ImageBytes).ToList();
var gestureRecognizer = new UILongPressGestureRecognizer(this, new ObjCRuntime.Selector("ImageLongPressed:"));
gestureRecognizer.AddTarget(() => ImageLongPressed(gestureRecognizer));
// Populate the image views.
// TODO need to find a way to assign it to every imageview on the view without looping maybe linq???
int i = 0;
foreach (var item in imageBytes)
{
var imagedata = NSData.FromArray(item);
var img = UIImage.LoadFromData(imagedata);
if (uIImageViews != null && uIImageViews.Count > i)
{
uIImageViews[i].UserInteractionEnabled = true;
uIImageViews[i].AddGestureRecognizer(gestureRecognizer);
uIImageViews[i].AddGestureRecognizer(gestureRecognizer);
uIImageViews[i].Image = img;
}
i++;
}
It depends on how you are creating your view, are you using a XIB with all the images on there as buttons with images, and IBActions connected to those buttons. just make the sender a UILongPressGestureRecognizer.
If you are doing it through code, then in your ViewDidLoad you want to set your buttons to have an initial ? (or Image Needed) background image and then you add the UILongPress GestureRecognizer to each on of them. So if you had one button, you would do this:
public override void ViewDidLoad ()
{
// Perform any additional setup after loading the view
UIButton button = new UIButton (new System.Drawing.RectangleF(100, 100, 100, 30));
button.SetBackgroundImage ("imageNeeded", UIControlState.Normal);
var gestureRecognizer = new UILongPressGestureRecognizer ();
gestureRecognizer.AddTarget(() => this.ButtonLongPressed(gestureRecognizer));
button.AddGestureRecognizer(gestureRecognizer);
this.View.Add (button);
}
public void ButtonLongPressed(UILongPressGestureRecognizer gestureRecognizer)
{
if (gestureRecognizer.State != UIGestureRecognizerState.Began)
{
return;
// Needed because selector is executed twice, because Long-press gestures are continuous
}
// Perform action of opening the dialog to select/take a picture, replacing the ? image with the new image
}
If want to use UILongPressGestureRecognizer in UIImage, should set ImageView's UserInteractionEnabled be true.
As follow:
List<UIImageView> imageViews = new List<UIImageView>();
UIImage image = UIImage.FromFile("off.png");
ImageViewOne.Image = image;
ImageViewOne.Tag = 1;
ImageViewTwo.Image = image;
ImageViewTwo.Tag = 2;
imageViews.Add(ImageViewOne);
imageViews.Add(ImageViewTwo);
foreach (var imageview in imageViews)
{
imageview.UserInteractionEnabled = true;
UILongPressGestureRecognizer uITapGestureRecognizer = new UILongPressGestureRecognizer();
uITapGestureRecognizer.AddTarget(() => { Console.WriteLine("You choose View " + imageview.Tag); });
imageview.AddGestureRecognizer(uITapGestureRecognizer);
}
Here is official document from Apple.

Move and Jump animation for UIImageView : Swift 4

I need to make my image jump and move down with animation. I am using sprites to show the jump animation. But, when I try to combine it with move down animation, it does not work. I am trying it on click of a button. Below is my code.
My animation works properly for second click but for first click it just jumps at its current location and at second click it jumps and moves down. I am trying to make it jump and move down at first button click.
#IBAction func targetTouchAction(_ sender: Any) {
let images: [UIImage] = (1...10).map { return UIImage(named: "Jump_\($0)")! }
self.jackImage.frame.origin.y = self.jackImage.frame.origin.y + 100.0
self.jackImage.animationImages = images
self.jackImage.animationDuration = 2.0
self.jackImage.animationRepeatCount = 1
self.jackImage.startAnimating()
}
I am trying this from last two three hours but no luck.
You are mixing 2 different types of animation. Don't do that. Using the animationImages property of a UIImageView is separate from using UIView animation methods like UIView.animate(duration:animations:)
Get rid of that UIView animation wrapper, and just specify the animation images and other settings for your image view:
#IBAction func targetTouchAction(_ sender: Any) {
let jumpImages = ["Jump_1","Jump_2","Jump_3","Jump_4","Jump_5","Jump_6","Jump_7","Jump_8","Jump_9","Jump_10"]
var images = [UIImage]()
for image in jumpImages{
images.append(UIImage(named: image)!)
}
self.imageView.frame.origin.y = self.imageView.frame.origin.y + 100.0
self.imageView.animationImages = images
self.imageView.animationDuration = 2.0
self.imageView.animationRepeatCount = 1
self.imageView.startAnimating()
}
Note that loading the array of images into the image view each time you trigger the animation is unnecessary, but it should still work.
I haven't worked with SpriteKit, so I'm not sure how your image view animation will interact with that. (Plus you didn't show that part of your code.)
Also, note that you could create your array of images with 1 line of code, and without using a hard-coded array of filenames:
let images: [UIImage] = (1...10).map { return UIImage(named: "Jump_\($0)") }
That code creates a sequence from 1 to 10. It then uses the map statement to map that sequence into an array of images by feeding the value into a string, and using that string as the image name in a call to UIImage(named:)

Change UIBarButtonIcon in an if and else statement in Swift

Inside of an If and else statement I want to change the custom image of my BarButtonItem. How can I Do these by default I already have one custom Image but know I want that under some circumstances it changes to another custom Image.
If you have your images in Assets.xcassets you can do this:
if something {
yourBarButtonItem.image = imagename
} else {
yourBarButtonItem.image = anotherimagename
}
that should work. Else, if you have your image just in a folder inside your project you can to this:
if something {
yourBarButtonItem.image = UIImage(named: "imagename.extension")
} else {
yourBarButtonItem.image = UIImage(named: "imagename.extension")
}

Remove uiimageview from view

I have a feed and i am wanting to display images if the user does not have an image, it will say null in the json. if the user does have a image, the image will be set with the image url.
i want to remove it so it will not take up space in the tableview cell.
my code is:
if imageStringFromJson == nil {
//how do i remove the imageview? <-- need help here
} else {
//set image from url in imageview
}
Try:
imageView.removeFromSuperview()
Or:
imageView.hidden = true
Or animate:
UIView.animateWithDuration(1) {
imageView.alpha = 0
}
To animate back to showing, try this:
UIView.animateWithDuration(1) {
imageView.alpha = 1
}