Hello, I'm new to Swift and I'm not understanding why the image stretches when I turn a page using PageViewController
as I'll show in the image below:
This image is normal, that's when I have not turned the page yet.
ButnowistheimageofwhenIturnapageforwardandreturntothehomepageafter:
NowI'mgoingtopostmycodeforreview:
importUIKitimportCoreDataclassViewControllerRevistaImagem:UIViewController,UIPageViewControllerDataSource,UIPageViewControllerDelegate{vararrPageTitle:NSArray=NSArray()vararrPagePhoto:NSMutableArray=NSMutableArray()vararrPagePhoto1:NSMutableArray=NSMutableArray()vararrInteiro:NSMutableArray=NSMutableArray()varappDelegate:AppDelegate!varmanagedContext:NSManagedObjectContext!varviewDidload:Int=Int()varpageViewController:UIPageViewController!lazyvarmodelController=ModelController()vardataPunicao:NSDate!varwiewwilappear:Int=0varx=0overridefuncviewDidLoad(){super.viewDidLoad()self.navigationController?.hidesBarsOnTap=trueself.pageViewController=UIPageViewController(transitionStyle:.pageCurl,navigationOrientation:.horizontal,options:nil)self.pageViewController!.delegate=selfself.pageViewController.view.clipsToBounds=trueifarrPagePhoto.count!=0{arrPagePhoto.removeAllObjects()}appDelegate=UIApplication.shared.delegateas!AppDelegatemanagedContext=appDelegate.managedObjectContextdo{varuser1:NSManagedObject!varuser2:NSManagedObject!vartitulo2:String=String()vartitulo3:String=String()letmyFetchRequest=NSFetchRequest<NSFetchRequestResult>(entityName:"Noticias")
myFetchRequest.returnsObjectsAsFaults = false
let sortDescriptor = NSSortDescriptor(key: "voto", ascending: false)
let sortDescriptors = [sortDescriptor]
myFetchRequest.sortDescriptors = sortDescriptors
var myFetchResults : [NSManagedObject] = try managedContext.fetch(myFetchRequest) as! [NSManagedObject]
if(!myFetchResults.isEmpty)
{
var i = 0
if myFetchResults.count >= 2 && myFetchResults[1].value(forKey: "titulo") != nil
{
user1 = myFetchResults[1]
titulo2 = (user1.value(forKey: "titulo") as? String)!
}
if myFetchResults.count >= 3 && myFetchResults[2].value(forKey: "titulo") != nil
{
user2 = myFetchResults[2]
titulo3 = (user2.value(forKey: "titulo") as? String)!
}
while(i < myFetchResults.count)
{
let user : NSManagedObject = myFetchResults[i]
if user.value(forKey: "foto") != nil
{
if i == 0
{
let primeiraPagina = UIImage(named: "imagens/2.jpg")
let primeiraPagina2 = UIImageJPEGRepresentation(primeiraPagina!, 0)
arrPagePhoto.add(primeiraPagina2)
arrInteiro.add(i)
var imagem2 : UIImage = UIImage()
var imagem2Capa1 : UIImage = UIImage()
var imagem2Capa2 : UIImage = UIImage()
var imagem2Fundo1 : UIImage = UIImage()
var imagem2Fundo2 : UIImage = UIImage()
var imagem3 : Data!
var imagem3Capa1 : Data!
var imagem3Capa2 : Data!
var imagem3Fundo1 : Data!
var imagem3Fundo2 : Data!
if user.value(forKey: "imagem") != nil && user.value(forKey: "titulo") != nil
{
let imagem = user.value(forKey: "imagem") as? Data
let titulo = user.value(forKey: "titulo") as? String
imagem2 = textToImage( titulo! as NSString , inImage : UIImage(data: imagem!)! , inImageFundo : UIImage(named: "imagens/fundo.jpg")! ,atPoint:CGPoint(x: 0 , y: 0) , tipoImagem : 1)
imagem3 = UIImageJPEGRepresentation(imagem2, 0)
arrPagePhoto.add(imagem3)
arrInteiro.add(i)
}
if user1 != nil && user1.value(forKey: "foto") != nil
{
let imagemCapa1 = user1.value(forKey: "imagem") as? Data
arrPagePhoto1[0] = (imagemCapa1)
//---------------------------------------------------------------------------------
imagem2Fundo1 = textToImage( titulo2 as NSString , inImage : UIImage(data: imagemCapa1!)! , inImageFundo :UIImage(named: "imagens/fundo.jpg")! , atPoint:CGPoint(x: 0, y: 5
) , tipoImagem: 3)
imagem3Fundo1 = UIImageJPEGRepresentation(imagem2Fundo1, 0)
arrPagePhoto1[1] = (imagem3Fundo1)
}
if user2 != nil && user2.value(forKey: "foto") != nil
{
let imagemCapa2 = user2.value(forKey: "imagem") as? Data
arrPagePhoto1[2] = (imagemCapa2)
//---------------------------------------------------------------------------------
imagem2Fundo2 = textToImage( titulo3 as NSString , inImage : UIImage(data: imagemCapa2!)! , inImageFundo :UIImage(named: "imagens/fundo.jpg")! , atPoint:CGPoint(x: 0, y: 20) , tipoImagem: 5)
imagem3Fundo2 = UIImageJPEGRepresentation(imagem2Fundo2, 0)
arrPagePhoto1[3] = (imagem3Fundo2)
}
}
arrPagePhoto.add((user.value(forKey: "foto") as? Data)!)
arrInteiro.add(i)
}
i += 1
}
}
}
catch
{
print("Erro na leitura")
}
if arrPagePhoto.count > 0
{
self.pageViewController!.setViewControllers([getViewControllerAtIndex(0)] as [UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil)
let startingViewController: PageContentViewController = self.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: pageViewController.view , attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: topLayoutGuide, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
let bottomConstaint = NSLayoutConstraint(item: pageViewController.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: bottomLayoutGuide, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: pageViewController.view, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.leading, multiplier: 3.0, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: pageViewController.view, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0)
view.addConstraints([topConstraint, bottomConstaint , leadingConstraint , trailingConstraint])
}
var pageViewRect = self.view.bounds
if UIDevice.current.userInterfaceIdiom == .pad {
pageViewRect = pageViewRect.insetBy(dx: 40.0, dy: 40.0)
}
self.pageViewController!.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width , height: self.view.frame.height)
self.pageViewController!.didMove(toParentViewController: self)
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func viewDidAppear(_ animated: Bool) {
print("2")
let filepath : String = self.getFilePath()
if(FileManager.default.fileExists(atPath: filepath))
{
let array : NSArray = NSArray(contentsOfFile: filepath)!
dataPunicao = array.object(at: 3) as! NSDate
if dataPunicao.compare(NSDate() as Date) == .orderedDescending
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let resultadoController: MensagemBloqueio = storyboard.instantiateViewController(withIdentifier: "MensagemBloqueio") as! MensagemBloqueio
present(resultadoController, animated: true, completion: nil)
}
}
}
func textToImage(_ drawText: NSString,inImage: UIImage, inImageFundo : UIImage , atPoint:CGPoint , tipoImagem : Int)->UIImage{
var tamanhoIdealMin : CGFloat = CGFloat()
var tamanhoIdealAlt : CGFloat = CGFloat()
var tamanhoIdealLarg : CGFloat = CGFloat()
tamanhoIdealMin = 100
tamanhoIdealAlt = 500
tamanhoIdealLarg = 3000
let textColor: UIColor = UIColor.black
let widthImagem = inImage.size.width
let heightImagem = inImage.size.height
var tamanhoLegenda : CGFloat = CGFloat()
if tipoImagem == 1
{
if heightImagem > widthImagem
{
let quantasVezes : CGFloat = heightImagem - 100
tamanhoLegenda = 7 + quantasVezes * 0.05
}
else if heightImagem < widthImagem || heightImagem == widthImagem
{
let quantasVezes : CGFloat = widthImagem - 100
tamanhoLegenda = 7 + quantasVezes * 0.07
}
}
else
{
tamanhoLegenda = 32
}
let textFont: UIFont = UIFont(name: "Helvetica Bold", size: tamanhoLegenda)!
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let scale = UIScreen.main.scale
print("scale : \(scale)")
print("inimage.size : \(inImage.size)")
if tipoImagem == 3 || tipoImagem == 5
{
UIGraphicsBeginImageContextWithOptions(inImageFundo.size, false , scale)
}
else
{
UIGraphicsBeginImageContextWithOptions(inImage.size , false , scale)
}
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: paragraphStyle
]
if tipoImagem == 1
{
print("entrou tipo imagem 1")
if inImage.size.width > inImage.size.height && inImage.size.width >= tamanhoIdealMin && inImage.size.height >= tamanhoIdealMin
{
print("entrou tipo imagem 1 if ")
let width = inImage.size.width
var height = inImage.size.height
print("largura : \(width) e altura : \(height)")
let porcentagemAltura = (height / width) * 100
//0,75
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = NumberFormatter.Style.percent
percentFormatter.multiplier = 1
percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 1
let porcentagem = percentFormatter.string(from: NSNumber(value: Int(porcentagemAltura)))
let porcentagemNumero = CGFloat(percentFormatter.number(from: porcentagem!)!)
height = (porcentagemNumero/100) * tamanhoIdealLarg
print("height : \(height)")
print("widhth : \(width)")
inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width , height: inImage.size.height))
let alturaTitulo : CGFloat = inImage.size.height/3 * 2
let rect: CGRect = CGRect(x: atPoint.x, y: alturaTitulo , width: inImage.size.width, height: inImage.size.height)
drawText.draw(in: rect, withAttributes: textFontAttributes)
}
else if inImage.size.width < inImage.size.height && inImage.size.height >= tamanhoIdealMin && inImage.size.width >= tamanhoIdealMin
{
let width = inImage.size.width
var height = inImage.size.height
let porcentagemAltura = (height / width) * 100
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = NumberFormatter.Style.percent
percentFormatter.multiplier = 1
percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 1
let porcentagem = percentFormatter.string(from: NSNumber(value: Int(porcentagemAltura)))
let porcentagemNumero = CGFloat(percentFormatter.number(from: porcentagem!)!)
height = (porcentagemNumero/100) * tamanhoIdealLarg
inImage.draw(in: CGRect(x: 0, y: 0 , width: tamanhoIdealLarg , height: height))
inImage.draw(in: CGRect(x: (inImage.size.width/2) - (tamanhoIdealLarg/2), y: ((tamanhoIdealLarg + 170)/2) - (height/2) , width: tamanhoIdealLarg , height: height))
let alturaTitulo : CGFloat = inImage.size.height/3 * 2.4
let rect: CGRect = CGRect(x: atPoint.x, y: alturaTitulo , width: inImage.size.width, height: inImage.size.height)
drawText.draw(in: rect, withAttributes: textFontAttributes)
}
}
else if tipoImagem == 3
{
inImageFundo.draw(in: CGRect(x: 0, y: 0, width: 250 , height: 250))
let rect: CGRect = CGRect(x: atPoint.x, y: atPoint.y , width: inImageFundo.size.width , height: inImageFundo.size.width)
drawText.draw(in: rect, withAttributes: textFontAttributes)
}
else if tipoImagem == 4
{
inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height))
}
else if tipoImagem == 5
{
inImageFundo.draw(in: CGRect(x: 0, y: 0, width: 250, height: 250))
let rect: CGRect = CGRect(x: atPoint.x, y: atPoint.y , width:inImageFundo.size.width , height: inImageFundo.size.height)
drawText.draw(in: rect, withAttributes: textFontAttributes)
}
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
print("print3")
let pageContent: PageContentViewController = viewController as! PageContentViewController
var index = pageContent.pageIndex
if ((index == 0) || (index == NSNotFound)) {
return nil
}
index -= 1;
return getViewControllerAtIndex(index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
print("print4")
let pageContent: PageContentViewController = viewController as! PageContentViewController
var index = pageContent.pageIndex
if (index == NSNotFound) { return nil; }
index += 1;
if (index == arrPagePhoto.count) { return nil; }
return getViewControllerAtIndex(index)
}
func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
if (orientation == .portrait) || (orientation == .portraitUpsideDown) || (UIDevice.current.userInterfaceIdiom == .phone) {
// In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
/*
let currentViewController = self.pageViewController!.viewControllers![0]
let viewControllers = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: true, completion: {done in })
*/
//print("portrait")
//self.pageViewController!.isDoubleSided = false
//return .min
}
let currentViewController : PageContentViewController = self.pageViewController!.viewControllers![0] as! PageContentViewController
var viewControllers: [UIViewController]
let indexOfCurrentViewController = self.indexOfViewController(currentViewController)
if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
let nextViewController = self.pageViewController(self.pageViewController!, viewControllerAfter: currentViewController)
viewControllers = [currentViewController, nextViewController!]
} else {
let previousViewController = self.pageViewController(self.pageViewController!, viewControllerBefore: currentViewController)
viewControllers = [previousViewController!, currentViewController]
}
self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: true, completion: {done in })
return .mid
}
func getViewControllerAtIndex(_ index: NSInteger) -> PageContentViewController
{
let pageContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "PageContentViewController") as! PageContentViewController
pageContentViewController.strPhotoName = UIImage(data:arrPagePhoto[index] as! Data)!
if index == 1
{
if arrPagePhoto1.count >= 1
{
pageContentViewController.strPhotoName1 = UIImage(data:arrPagePhoto1[0] as! Data)!
}
if arrPagePhoto1.count >= 2
{
pageContentViewController.strPhotoName2 = UIImage(data:arrPagePhoto1[1] as! Data)!
}
if arrPagePhoto1.count >= 3
{
pageContentViewController.strPhotoName3 = UIImage(data:arrPagePhoto1[2] as! Data)!
}
if arrPagePhoto1.count >= 4
{
pageContentViewController.strPhotoName4 = UIImage(data:arrPagePhoto1[3] as! Data)!
}
}
pageContentViewController.pageIndex = index
return pageContentViewController
}
func indexOfViewController(_ viewController: PageContentViewController) -> Int {
if let dataObject: AnyObject = viewController.pageIndex as AnyObject? {
return self.arrInteiro.index(of: dataObject)
} else {
return NSNotFound
}
}
func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) ->
PageContentViewController? {
if (self.arrPagePhoto.count == 0 || (index >= self.arrPagePhoto.count)){
return nil
}
let viewControllerId: NSString = "PageContentViewController"
let pageContentViewController = storyboard.instantiateViewController(withIdentifier: viewControllerId as String) as! PageContentViewController
pageContentViewController.strPhotoName = UIImage(data:arrPagePhoto[index] as! Data)!
if index == 1
{
if arrPagePhoto1.count >= 1
{
pageContentViewController.strPhotoName1 = UIImage(data:arrPagePhoto1[0] as! Data)!
}
if arrPagePhoto1.count >= 2
{
pageContentViewController.strPhotoName2 = UIImage(data:arrPagePhoto1[1] as! Data)!
}
if arrPagePhoto1.count >= 3
{
pageContentViewController.strPhotoName3 = UIImage(data:arrPagePhoto1[2] as! Data)!
}
if arrPagePhoto1.count >= 4
{
pageContentViewController.strPhotoName4 = UIImage(data:arrPagePhoto1[3] as! Data)!
}
}
pageContentViewController.pageIndex = index
return pageContentViewController
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask
{
return UIInterfaceOrientationMask.all
}
func getFilePath() -> String
{
let userDomainPaths : NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let filePath : String = userDomainPaths.object(at: 0) as! String
return "\(filePath)myFile.plist"
}
}
and also:
import UIKit
class PageContentViewController: UIViewController {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageView1: UIImageView!
@IBOutlet weak var imageView2: UIImageView!
@IBOutlet var imageViewFundo1: UIImageView!
@IBOutlet var imageViewFundo2: UIImageView!
@IBOutlet weak var blurView: UIImageView!
var dataObject: AnyObject?
var pageIndex: Int = 0
var strTitle: String!
var strPhotoName: UIImage = UIImage()
var strPhotoName1: UIImage = UIImage()
var strPhotoName2: UIImage = UIImage()
var strPhotoName3: UIImage = UIImage()
var strPhotoName4: UIImage = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = strPhotoName
imageView1.image = strPhotoName1
imageView2.image = strPhotoName2
imageViewFundo1.image = strPhotoName3
imageViewFundo2.image = strPhotoName4
blurView.image = strPhotoName
if pageIndex == 1
{
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView1.contentMode = .scaleAspectFit
imageViewFundo1.contentMode = .scaleAspectFit
self.imageView.backgroundColor = UIColor.clear
let bluerEfect = UIBlurEffect(style: UIBlurEffectStyle.light)
let bluerView = UIVisualEffectView(effect: bluerEfect)
bluerView.frame = blurView.bounds
bluerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bluerView.alpha = 0.9
blurView.addSubview(bluerView)
self.imageView.frame = CGRect(x: 0, y: 0, width: 333.5, height: 200)
self.blurView.frame = CGRect(x: 0, y: 0, width: 333.5, height: 400)
}
}
And in sotryboard I added 4 constraints on the pin as shown in the image below:
And that's all I did, any help thanks.