Hide subview image once the view has loaded (using Swift) - ios

Technologies: XCode6, iOS 8.2, Swift
When the view loads, I add an image:
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
self.navigationController?.toolbarHidden = false;
openLoadingPopup()
if browserHistory.count < 1 {
backButton.enabled = false
}
let imageName = UIImage(named: "image.png")
let imageview = UIImageView(image: imageName)
imageview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.view.addSubview(imageview)
}
And I want to remove that image here (if possible). Best way to do that?
func webViewDidFinishLoad(webView: UIWebView) {
UIApplication.sharedApplication()
. networkActivityIndicatorVisible = false
closeLoadingPopup()
if cacheURL {
++browserHistoryIndex
browserHistory.insert(webView.request!.URL, atIndex: browserHistoryIndex)
backButton.enabled = browserHistoryIndex != 0
//forwardButton.enabled = browserHistoryIndex != browserHistory.count - 1
}
if webView.request!.URL == lastURL {
cacheURL = true
}
}

Make imageView a property instead of a local variable, and use imageView.removeFromSuperview() in the webViewDidFinishLoad method.

Related

how to make save button to swift 5?

I'm creating a wallpaper app for iOS. I've created a UIImageView, but am stuck on saving the image. I have solved the permissions but am unable to have the user save the image. I created the save button itself, but I don't know to make save any image from the image array in the user's image gallery.
Here is my code so far:
class ViewController: UIViewController {
#IBOutlet var imageview: [UIScrollView]!
#IBOutlet weak var saveButton: UIButton!
#IBAction func saveButtonPressed(_ sender: UIButton) {
// TODO: - How to save the image here
}
let scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.isPagingEnabled = true
scroll.showsVerticalScrollIndicator = false
scroll.showsHorizontalScrollIndicator = false
scroll.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
return scroll
}()
var imageArray = [UIImage]()
func setupImages(_ images: [UIImage]){
for i in 0..<images.count {
let imageView = UIImageView()
imageView.image = images[i]
let xPosition = UIScreen.main.bounds.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
imageView.contentMode = .scaleAspectFit
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
//scrollView.delegate = (self as! UIScrollViewDelegate)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(scrollView)
imageArray = [#imageLiteral(resourceName: "1"),#imageLiteral(resourceName: "10"),#imageLiteral(resourceName: "9"),#imageLiteral(resourceName: "8"),#imageLiteral(resourceName: "3")]
setupImages(imageArray)
}
}
You will need to add a saveImage function:
func saveImage(image: UIImage) -> Bool {
guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent("fileName.png")!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
And then in saveButtonPressed:
let success = saveImage(image: imageArray[0])
print("Did \(success ? "" : "not ")store image successfully")
You'll need to add some logic to actually select the image.

Animate thru various images in Swift - Using customized Load View

I have a customLoader which I would like to call anytime a user logs in. I want to animate thru all seven photos in gifArray.
import UIKit
class CustomLoader: UIView {
static let instance = CustomLoader()
let gifArray: [UIImage] = [UIImage(named: "beer1")!,UIImage(named: "beer2")!,UIImage(named: "beer3")!,UIImage(named: "beer4")!,UIImage(named: "beer5")!,UIImage(named: "beer6")!,UIImage(named: "beer7")!]
lazy var transparentView:UIView = {
let transparentView = UIView(frame: UIScreen.main.bounds)
transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
transparentView.isUserInteractionEnabled = false
return transparentView
} ()
lazy var gifImage: UIImageView = {
var gifImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 200.00, height: 100))
gifImage.contentMode = .scaleAspectFit
gifImage.center = transparentView.center
gifImage.isUserInteractionEnabled = false
return gifImage
} ()
func animate() {
for image in gifArray {
gifImage.image = image
gifImage.animationRepeatCount = 1
gifImage.startAnimating()
}
}
func showLoader() {
self.addSubview(transparentView)
self.transparentView.addSubview(gifImage)
self.transparentView.bringSubviewToFront(self.gifImage)
animate()
}
func hideLoader() {
self.transparentView.removeFromSuperview()
}
}
I call it when the user logs in
In ViewDidLoad:
CustomLoader.instance.showLoader()
view.addSubview(CustomLoader.instance.transparentView)
view.bringSubviewToFront(CustomLoader.instance.transparentView)
Problem: It unfortunately just shows the last image. How do i fix this?
The for loop here sets the last image
for image in gifArray {
instead you need
gifImage.isUserInteractionEnabled = false
gifImage.animationImages = gifArray
Then
func animate() {
gifImage.startAnimating()
}

tapgesture not working in collectionViewCell, Neither any UIElements is visible on cell which is added by storyboard

I have a collectionViewCell that either plays a video or displays and image.Now the elements in the cell are generated programatically. I added tap gesture to toggle the sound when video play. The gesture recognizer wasn't getting called. I tried to place a button in story and get its action, that also didn't recieve a call. Then, I tried to place a view inside the cell, that also didn't display.
Here is my code with tap gesture:
import UIKit
import AVKit
import AVFoundation
#IBDesignable class CHCollectionImageCell: UICollectionViewCell {
// MARK: Properties
var imgView: UIImageView! = UIImageView()
var screenWidth:CGFloat = 0
var screenHeight:CGFloat = 0
var playerLayer: AVPlayerLayer!
let tapOnCell = UITapGestureRecognizer(target: self, action: #selector (CHCollectionImageCell.changeMuteRegimeVideo))
// MARK: Functions
override func awakeFromNib() {
super.awakeFromNib()
}
func configureCell(insight: InsightModel) {
imgView.removeFromSuperview()
if playerLayer != nil {
playerLayer.removeFromSuperlayer()
playerLayer = nil
}
self.removeGestureRecognizer(tapOnCell)
if insight.isVideo {
guard let unwrappedVideoURLString = insight.videoURL,
let unwrappedVideoURL = URL(string: unwrappedVideoURLString) else {
return
}
let playerItem = AVPlayerItem(url: unwrappedVideoURL)
let player = AVPlayer(playerItem: playerItem)
playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.bounds
player.isMuted = false
layer.addSublayer(playerLayer)
addGestureRecognizer(self.tapOnCell)
} else {
imgView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.width)
imgView.image = UIImage(named: "stone")
imgView.contentMode = UIViewContentMode.scaleAspectFill
imgView.clipsToBounds = true
clipsToBounds = true
addSubview(self.imgView)
}
}
/*
#IBAction func tapToTurnOfSound(_ sender: Any) {
if isInsightViedo{
if let unwrappedPlayer = playerLayer.player {
unwrappedPlayer.isMuted = !unwrappedPlayer.isMuted
}
}
//Even Tried adding view as below in the cell
//let tapView = UIView()
//tapView.backgroundColor = ColorCodes.appThemeColor
//self.addSubview(tapView)
//self.bringSubview(toFront: tapView)
//tapView.addGestureRecognizer(tapOnCell)
}
*/
func configureCell() {
imgView.removeFromSuperview()
if playerLayer != nil {
playerLayer.removeFromSuperlayer()
playerLayer = nil
}
self.removeGestureRecognizer(tapOnCell)
imgView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.width)
imgView.image = UIImage(named: "stone")
imgView.contentMode = UIViewContentMode.scaleAspectFill
imgView.clipsToBounds = true
clipsToBounds = true
addSubview(self.imgView)
}
func changeMuteRegimeVideo() {
if let unwrappedPlayer = playerLayer.player {
unwrappedPlayer.isMuted = !unwrappedPlayer.isMuted
}
}
}
Iam doing the same thing in my application by using the following code :
let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(viewController.longPress(_:)))
longPressGesture.minimumPressDuration = 0.8
longPressGesture.delegate = self
collectionView.addGestureRecognizer(longPressGesture)
and then call the function:
func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
if longPressGestureRecognizer.state == UIGestureRecognizerState.began {
let touchPoint = longPressGestureRecognizer.location(in: collectionView)
if eventsTableView.indexPathForRow(at: touchPoint) != nil {
let index = eventsTableView.indexPathForRow(at: touchPoint)//do whatever you want to do with this index
}}}
you can do whatever you want to do in this function. In my case i used this to enlarge the image in the collection view

How to apply an animation effect to UIImageView slideshow

On Swift 3.0 how can I apply some animation effect to this slideshow? Cannot find animation effects related to animationWithDuration method.
let image1 = UIImage(named: "image1")!
let image2 = UIImage(named: "image2")!
let image3 = UIImage(named: "image3")!
var imagesArray : [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
imagesArray = [image1, image2, image3]
myView.clipsToBounds = true
myView.animationImages = imagesArray
myView.animationDuration = 10.0
myView.animationRepeatCount = 0
myView.startAnimating()
}
It looks like you are using the build in frame animation for UIImageView. This is designed to just cycle through the images, like an animated gif. It doesn't really have more sophisticated animation than that. What you can do if you want transition effects is alternate between two image views and use the UIView Animation methods to switch between them. This just does a crossfade by manipulating alpha:
var images = [UIImage]()
var currentImageindex = 0
func animateImageViews() {
swap(&firstImageView, &secondImageView)
secondImageView.image = images[currentImageindex]
currentImageindex = (currentImageindex + 1) % images.count
UIView.animate(withDuration: 1, animations: {
self.firstImageView.alpha = 0
self.secondImageView.alpha = 1
}, completion: { _ in
self.animateImageViews()
})
}
Here is playground that shows how it works. You need to drop 2 images into the resources folder named 1.png and 2.png for it to work. Note that setting the view frames like this is horrible programming practice i just did it here for brevity. use interface builder and autolayout in your actual code.
import PlaygroundSupport
import UIKit
class Demo: UIViewController {
let button = UIButton()
var firstImageView = UIImageView()
var secondImageView = UIImageView()
var images = [UIImage]()
var currentImageindex = 0
override func viewDidLoad() {
view.addSubview(firstImageView)
view.addSubview(secondImageView)
images.append(UIImage(named: "1.png")!)
images.append(UIImage(named: "2.png")!)
firstImageView.image = images[0]
secondImageView.image = images[1]
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
firstImageView.frame = view.frame
secondImageView.frame = view.frame
}
override func viewDidAppear(_ animated: Bool) {
animateImageViews()
}
func animateImageViews() {
swap(&firstImageView, &secondImageView)
secondImageView.image = images[currentImageindex]
currentImageindex = (currentImageindex + 1) % images.count
UIView.animate(withDuration: 1, animations: {
self.firstImageView.alpha = 0
self.secondImageView.alpha = 1
}, completion: { _ in
self.animateImageViews()
})
}
}
let viewcontroller = Demo()
viewcontroller.view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
PlaygroundPage.current.liveView = viewcontroller.view

Changing Background on orientation change fails

I have two images bg-land and bg-port for different orientation. I wanna change the image on chnaging orientation. But, the image does not change. When I load the Simulator in LandScape, bg-land works perfect but does not work with Rotation. Code:
override func viewDidLoad() {
super.viewDidLoad()
loadBackground()
}
func loadBackground(){
if(UIApplication.sharedApplication().statusBarOrientation.isPortrait){
var bgImage = UIImage(named: "bg-port")
var background = UIImageView(frame: self.view.bounds);
background.image = bgImage
self.view.addSubview(background)
self.view.sendSubviewToBack(background)
println(bgImage)
} else {
var bgImage = UIImage(named: "bg-land")
var background = UIImageView(frame: self.view.bounds);
background.image = bgImage
self.view.addSubview(background)
self.view.sendSubviewToBack(background)
println(bgImage)
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
loadBackground()
}
This code works fine for me try this:
override func viewDidLoad() {
super.viewDidLoad()
self.loadBackground()
}
func loadBackground(){
if(UIApplication.sharedApplication().statusBarOrientation.isPortrait){
let imageName = "Texture.jpg"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = self.view.bounds
view.addSubview(imageView)
} else {
let imageName = "AppIcon.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = self.view.bounds
view.addSubview(imageView)
}
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
loadBackground()
}
Don't forget to change image name from this code.
May be this will help you.
It's not changing because you are sending the newly added UIImageView to the back of your previously created UIImageView. Instead of doing that, create a member variable in your class for UIImageView. (Name it as background)
func loadBackground()
{
if self.background == nil
{
self.background = UIImageView()
self.view.addSubview(self.background)
self.view.sendSubviewToBack(self.background)
}
if(UIApplication.sharedApplication().statusBarOrientation.isPortrait)
{
var bgImage = UIImage(named: "bg-port")
self.background.frame = self.view.bounds;
self.background.image = bgImage
}
else
{
var bgImage = UIImage(named: "bg-land")
self.background.frame = self.view.bounds;
background.image = bgImage
}
}
But it is better to add a UIImageView outlet to your interface and loading the image using code, rather than creating one at run-time. And I prefer that would be a nice approach.

Resources