Editor place holder in source file - swift2

I don't understand the problem here, my code has no bugs, but when I hit run nothing appears on the emulator. I need help, how can I see my images appear as a Scrollview on the emulator ?
import UIKit
class ViewController: UIViewController {
#IBOutlet var mainScrollView: UIScrollView!
var imageArray = [UIImage]()
override func viewDidLoad() {
mainScrollView.frame = view.frame
super.viewDidLoad()
imageArray = [#imageLiteral(resourceName: "IMG_1750"), #imageLiteral(resourceName: "IMG_1754")]
for i in 0..<imageArray.count{
let imageView = UIImageView()
imageView.image = imageArray[i]
imageView.contentMode = .scaleAspectFit
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)
mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat( i + 1)
mainScrollView.addSubview(imageView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

UIImage inside UIImageView is not scalling to fit

I receive a high resolution images from API, and I need to scale to fit them to my collection view cells. I'm using scaleToFit in UIImageView init but images are still in original ratio, moreover if I start to scroll in some moment they will get in full size
Cell:
final class SnapCarouselCellImpl: UICollectionViewCell, SnapCarouselCell{
var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleToFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
imageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
}
VC:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SnapCarouselCell", for: indexPath) as! SnapCarouselCellImpl
let item = items[indexPath.row % items.count]
cell.imageView.image = UIImage(data: item.poster)
return cell
}
private func setUpCollectionView() -> UICollectionView{
let collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: flowLayout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: cellHeight * 1.2)
collectionView.decelerationRate = .init(rawValue: 20)
collectionView.register(SnapCarouselCellImpl.self, forCellWithReuseIdentifier: "SnapCarouselCell")
return collectionView
}
FlowLayout:
override func prepare() {
scrollDirection = .horizontal
minimumLineSpacing = 20
itemSize = CGSize(width: cellWidth, height: cellHeight)
let sideMargin = (collectionView!.bounds.width - cellWidth) / 2.0
sectionInset = UIEdgeInsets(top: 0.0, left: sideMargin, bottom: 0.0, right: sideMargin)
}
Result:
After scrolling:
You didn't provide enough code to confirm this, but...
You can probably correct the issue by changing this line in init in your SnapCarouselCellImpl class from:
addSubview(imageView)
to:
contentView.addSubview(imageView)

Resign First Responder function in SKScene

I am trying to create a game that requires to create a textfield in SKScene. I have built the text field successfully, but bringing the keyboard down is the problem. This is my code so far.
import SpriteKit
import GameplayKit
import UIKit
class GameScene: SKScene {
var sceneFrame : CGRect = CGRect()
var textFieldFrame : CGRect = CGRect()
var textField : UITextField = UITextField()
var skView: SKView = SKView()
override func didMove(to view: SKView) {
sceneFrame = CGRect(origin: .zero, size: CGSize(width: 200, height: 200))
let scene = SKScene(size: sceneFrame.size)
scene.backgroundColor = UIColor.lightGray
textFieldFrame = CGRect(origin: .init(x: 100, y: 200), size: CGSize(width: 200, height: 30))
textField = UITextField(frame: textFieldFrame)
textField.backgroundColor = UIColor.white
textField.placeholder = "Phone Number"
textField.keyboardType = .numberPad
textField.resignFirstResponder()
self.view!.addSubview(textField)
self.view!.presentScene(scene)
// Where to put the textField.resignFirstResponder() ?
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
Any answers would be helpful.
The problem is you are not adding:
textfield.delegate = self
Then you could call the function:
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hides the keyboard
textField.resignFirstResponder()
return true
}
Declaring the delegate statement initiate the function textFieldShouldReturn.
Hope this helps :)

Xcode Swift image zoom gesture

Hope someone can help me. Im trying to make a zoom gesture, so when the image are presented the user can zoom the image with fingers.
My code to present the image are:
// MARK: Show image full screen
func imageTapped(img: AnyObject) {
self.navigationController?.navigationBarHidden = true
let imageView = productImage as UIImageView
let newImageView = UIImageView(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = .blackColor()
newImageView.contentMode = .ScaleToFill
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: "dismissFullscreenImage:")
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
func dismissFullscreenImage(sender: UITapGestureRecognizer) {
sender.view?.removeFromSuperview()
self.navigationController?.navigationBarHidden = false
}
Use UIScrollView and add UIImgeView in scroll view
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate
{
var scrollV : UIScrollView!
var imageView : UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
scrollV=UIScrollView()
scrollV.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
scrollV.minimumZoomScale=1
scrollV.maximumZoomScale=3
scrollV.bounces=false
scrollV.delegate=self;
self.view.addSubview(scrollV)
imageView=UIImageView()
imageView.image = UIImage(imageLiteral: "neymar.jpg")
imageView.frame = CGRectMake(0, 0, scrollV.frame.width, scrollV.frame.height)
imageView.backgroundColor = .blackColor()
imageView.contentMode = .ScaleToFill
scrollV.addSubview(imageView)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
{
return imageView
}
}
Take gesture programmatically and make its method and write down this code in the method.
pinchRecognizerOnView() is my method name. Take one view or image view inside view controller and add this new view in that.Now apply gesture method on this new view.
func pinchRecognizerOnView(sender: UIPinchGestureRecognizer!) {
sender.view?.transform = CGAffineTransformScale((sender.view?.transform)!, sender.scale, sender.scale)
sender.scale = 1
// its for zoom in out screen
}

swift multiple MPMoviePlayerController

hi I'm playing with the MPMoviePlayerController in swift
i have 2 MPMoviePlayerControllers I preload video in to each in view did load the second one plays from a button fine the first will play after the second has played? if I load the first one i get sound no picture but if play the second one then the first will then play fine?
here is a link to my testing
https://dl.dropboxusercontent.com/u/22927/videotest.zip
thanks for your help
import UIKit
import MediaPlayer
class ViewController: UIViewController
{
var moviePlayer : MPMoviePlayerController!
var moviePlayer2 : MPMoviePlayerController!
#IBOutlet weak var movieview: UIView!
#IBOutlet weak var movieview2: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
loadMovie()
loadMovie2()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func play2(sender: AnyObject)
{
moviePlayer2.play()
}
#IBAction func playbtn(sender: AnyObject)
{
moviePlayer.play()
}
func loadMovie()
{
let path = NSBundle.mainBundle().pathForResource("video1", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
moviePlayer.view.frame = CGRect(x: 0, y: 0, width: movieview.frame.size.width, height: movieview.frame.size.height )
moviePlayer.view.sizeToFit()
moviePlayer.scalingMode = MPMovieScalingMode.Fill
moviePlayer.fullscreen = false
moviePlayer.controlStyle = MPMovieControlStyle.None
moviePlayer.movieSourceType = MPMovieSourceType.File
moviePlayer.repeatMode = MPMovieRepeatMode.None
moviePlayer.prepareToPlay()
moviePlayer.pause()
movieview.addSubview( moviePlayer.view)
}
func loadMovie2()
{
let path = NSBundle.mainBundle().pathForResource("video2", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer2 = MPMoviePlayerController(contentURL: url)
moviePlayer2.view.frame = CGRect(x: 0, y: 0, width: movieview2.frame.size.width, height: movieview2.frame.size.height )
moviePlayer2.view.sizeToFit()
moviePlayer2.scalingMode = MPMovieScalingMode.Fill
moviePlayer2.fullscreen = false
moviePlayer2.controlStyle = MPMovieControlStyle.None
moviePlayer2.movieSourceType = MPMovieSourceType.File
moviePlayer2.repeatMode = MPMovieRepeatMode.None
moviePlayer2.prepareToPlay()
moviePlayer2.pause()
movieview2.addSubview( moviePlayer2.view)
}
}
import UIKit
import AVFoundation
import AssetsLibrary
import MediaPlayer
import CoreMedia
var player : AVPlayer? = nil
var playerLayer : AVPlayerLayer? = nil
var asset : AVAsset? = nil
var playerItem: AVPlayerItem? = nil
var loadingAssetOne = false
#IBOutlet weak var movieview: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func play2(sender: AnyObject)
{
loadingAssetOne = false
loadMovie()
}
#IBAction func playbtn(sender: AnyObject)
{
loadingAssetOne = true
loadMovie()
}
func loadMovie()
{
if loadingAssetOne
{
let path = NSBundle.mainBundle().pathForResource("video1", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
asset = AVAsset(URL: url) as AVAsset
playerItem = AVPlayerItem(asset: asset!)
player = AVPlayer (playerItem: self.playerItem!)
playerLayer = AVPlayerLayer(player: self.player)
movieview.frame = CGRectMake(38, 57, 220, 106)
playerLayer?.frame = movieview.frame
movieview.layer.addSublayer(self.playerLayer!)
player!.play()
}
else
{
let path = NSBundle.mainBundle().pathForResource("video1", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
asset = AVAsset(URL: url) as AVAsset
playerItem = AVPlayerItem(asset: asset!)
player = AVPlayer (playerItem: self.playerItem!)
playerLayer = AVPlayerLayer(player: self.player)
movieview.frame = CGRectMake(38, 206, 220, 106)
playerLayer?.frame = movieview.frame
movieview.layer.addSublayer(self.playerLayer!)
player!.play()
}
}
For more details,please go through the below source
Need to show multiple video using MPMoviePlayerController swift

From SWIFT Playground to custom View (IBDesignable?)

Question:
I've written a custom View Component in a playground but I can't figure out how to turn it into a custom class that I can use in the Interface Builder. Specifically, I'm confused as to how to make sure my custom view will resize correctly as the IB view is changed
Sub Question
I would also like to be able to use the #IBDesignable/#IBInspectable functionality as well if possible
Playground Code
import UIKit
let labelWidth : CGFloat = 200.0
var viewWidth : CGFloat = 200.0
let labelHeight: CGFloat = 60.0
var viewHeight : CGFloat = 60.0
let xOffset : CGFloat = 20
let yOffset : CGFloat = 20
let label = UILabel(frame: CGRectMake(0, 0 + 10, labelWidth, 50))
label.text = "Custom Text"
label.backgroundColor = UIColor.greenColor()
label.layer.masksToBounds = true
//label.layer.cornerRadius = 10.0
label.textAlignment = NSTextAlignment.Center
label
let titleLabel = UILabel(frame: CGRectMake(0,0,labelWidth,20))
titleLabel.font = UIFont(name: label.font.fontName, size: 10)
titleLabel.text = " TITLE"
titleLabel.layer.masksToBounds = true
titleLabel.backgroundColor = UIColor.whiteColor()
titleLabel
let v = UIView(frame: CGRectMake(0, 0, viewWidth, viewHeight))
v.backgroundColor = UIColor.grayColor()
v.addSubview(label)
v.addSubview(titleLabel)
v.layer.borderWidth = 1
v.layer.borderColor = UIColor.redColor().CGColor
v
Playground Visual Output
Note: Obviously these are not the final colors i want to use but they help differentiate the components
I just posted this answer for a similar question.
Here is a sample class to get you started.
import UIKit
#IBDesignable
class MyTabView: UIView {
#IBInspectable tabTitle: String = ""
#IBInspectable tabColor: UIColor = UIColor.clearColor()
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForInterfaceBuilder() {
// stuff for interface builder only
}
override func drawRect(rect: CGRect)
{
// this is where your view gets drawed
self.layer.cornerRadius = 10
self.layer.masksToBounds = true
}
}
Note: you only need to override drawRect if you need custom drawing.

Resources