Remove a UIView stored in an array from superview - objective-c

I know the code I need is [[Array objectAtIndex:index] removeFromSuperview]; but that doesn't work in Swift 2.
I'm trying to remove a UIView stored in an array from the superview. I know I want to remove the object at index 0. Want to remove it at the end of the for loop.
What code will work in Swift?
import UIKit
import Foundation
class PhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var tileStack = [AnyObject]()
let num = 0
//Beginning of simple image selection and display
#IBOutlet weak var displayImageView: UIImageView!
#IBOutlet weak var tiledView: UIImageView!
#IBAction func choosePicFromLibrary(sender: AnyObject) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
imagePicker.modalPresentationStyle = UIModalPresentationStyle.Popover
if (imagePicker.popoverPresentationController != nil) {
imagePicker.popoverPresentationController!.sourceView = sender as! UIButton
imagePicker.popoverPresentationController!.sourceRect = (sender as! UIButton).bounds
}
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func takePhoto(sender: AnyObject) {
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.delegate = self
imagePicker.modalPresentationStyle = UIModalPresentationStyle.Popover
if (imagePicker.popoverPresentationController != nil) {
imagePicker.popoverPresentationController!.sourceView = sender as! UIButton
imagePicker.popoverPresentationController!.sourceRect = (sender as! UIButton).bounds
}
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
displayImageView.image = info[UIImagePickerControllerOriginalImage] as! UIImage!
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
//Beginning of function to cut photo into 9 tiles, then display them randomly.
//cut selected image into 9 pieces and add each cropped image to tileStack array
#IBAction func randomize(sender: AnyObject) {
let selectedImageWidth = displayImageView.image!.size.width
let selectedImageHeight = displayImageView.image!.size.height
let tileSize = CGSizeMake(selectedImageWidth/3, selectedImageHeight/3)
for (var colI = 0; colI < 3; colI++)
{
for (var rowI = 0; rowI < 3; rowI += 1)
{
let tileRect = CGRectMake(CGFloat(rowI) * tileSize.width, tileSize.height * CGFloat(colI), tileSize.width, tileSize.height)
if let selectedImage = displayImageView.image
{
let tileImage = CGImageCreateWithImageInRect(selectedImage.CGImage, tileRect)
let aUItile = UIImage(CGImage: tileImage!)
tileStack.append(aUItile)
}
}
}
//display tiles in order on screen, remove 1 tile (top left, index 0), (eventually mix them up)
let frameWidth = self.view.frame.width
let frameHeight = self.view.frame.height
var xCen = (frameWidth/3)/2
var yCen = (frameHeight/3)/2
var pieceNumber = 0
for (var v = 0; v < 3; v += 1)
{
for (var h = 0; h < 3; h += 1)
{
var tiledView : UIImageView
tiledView = UIImageView(frame:CGRectMake(0, 0, frameWidth/3, (frameHeight)/3))
//tiledView.backgroundColor = UIColor.redColor()
tiledView.center = CGPointMake(xCen, yCen)
tiledView.image = tileStack[pieceNumber] as? UIImage
tiledView.userInteractionEnabled = true
self.view.addSubview(tiledView)
xCen += (frameWidth/3)
pieceNumber += 1
}
xCen = (frameWidth/3)/2
yCen += (frameHeight/3)
}
tileStack[0].removeFromSuperview()
tileStack.removeAtIndex(0)
}

In Swift 2.0, you need to call the removeFromSubview from the object that you want to remove. In your case you need the following:
dispatch_async(dispatch_get_main_queue(),
{
if self.view.subviews.count > 0
{
self.view.subviews[0].removeFromSuperview()
}
})

Related

How to asynchronous load image from a web-server in UICollectionView using NSCache

I have some issues when loading images from a web-server in UICollectionView using NScache.
The problem:
The images are not proper displayed:
sometimes they are not showned in the corresponding cell
or
the image is changing on scroll
Situation:
I have 3 arrays whitch are properly loaded from the web-server in function viewDidLoad(). These arrays are: vPrice, vTitle and vImages_api
my custom class for cell have:
label for price: cell.lblPrice
label for title: cell.lblTitle
image: cell.imgPicture
I belive that the problem is in function func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
It could be related either to the way I use NSCache or to the way I use and when I use DispatchQueue.
The code:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.collectionViewPRODUSE.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! clsCustomCell
cell.lblPrice.text = vPrice[indexPath.item]
cell.lblTitle.text = vTitle[indexPath.item]
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 0.5
DispatchQueue.global(qos: .userInitiated).async {
//background thread
let ImageString = self.vImages_api[indexPath.item]
let imageUrl = URL(string: ImageString)
let imageData = NSData(contentsOf: imageUrl!)
// main thread to update the UI
DispatchQueue.main.async {
let key1 = self.vImages_api[indexPath.item] as AnyObject
//if i saved allready my image in cache, then i will load my image from cache
if let imageFromCache = self.objCache.object(forKey: key1){
cell.imgPicture.image = imageFromCache as! UIImage
}
else{//if my image is not in cache ......
if imageData != nil {
let myPicture = UIImage(data: imageData! as Data)
cell.imgPicture.image = myPicture
//save my image in cache
self.objCache.setObject(myPicture!, forKey: ImageString as AnyObject)
}
}
}
}
return cell
}
Edited code - version II:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.collectionViewPRODUSE.dequeueReusableCell(withReuseIdentifier: "MyCustomCell", for: indexPath) as! clsCustomCell
cell.lblPret.text = vPrice[indexPath.item]
cell.lblTitlu.text = vTitle[indexPath.item]
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 0.5
let key1 = self.vImages_api[indexPath.item] as AnyObject
if let imageFromCache = self.objCache.object(forKey: key1){
cell.imgPicture.image = imageFromCache as! UIImage
}else{
DispatchQueue.global(qos: .background).async {
let ImageString = self.vImages_api[indexPath.item]
let imageUrl = URL(string: ImageString)
let imageData = NSData(contentsOf: imageUrl!)
let myPicture = UIImage(data: imageData! as Data)
self.objCache.setObject(poza!, forKey: ImageString as AnyObject)
DispatchQueue.main.async {
if imageData != nil {
cell.imgPicture.image = myPicture
}
}
}
}
return cell
}
Edited code - version III
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.collectionViewPRODUSE.dequeueReusableCell(withReuseIdentifier: "celula_custom", for: indexPath) as! clsCustomCell
cell.lblPret.text = vPrice[indexPath.item]
cell.lblTitlu.text = vTitle[indexPath.item]
NKPlaceholderImage(image: UIImage(named: "loading"), imageView: cell.imgPicture, imgUrl: self.vImages_api[indexPath.item]
) { (image11) in
cell.imgPicture.image = image11
}
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 0.5
return cell
}
Try this one it's Working code (Swift 4).
func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:#escaping (UIImage?) -> Void){
if image != nil && imageView != nil {
imageView!.image = image!
}
var urlcatch = imgUrl.replacingOccurrences(of: "/", with: "#")
let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
urlcatch = documentpath + "/" + "\(urlcatch)"
let image = UIImage(contentsOfFile:urlcatch)
if image != nil && imageView != nil
{
imageView!.image = image!
compate(image)
}else{
if let url = URL(string: imgUrl){
DispatchQueue.global(qos: .background).async {
() -> Void in
let imgdata = NSData(contentsOf: url)
DispatchQueue.main.async {
() -> Void in
imgdata?.write(toFile: urlcatch, atomically: true)
let image = UIImage(contentsOfFile:urlcatch)
compate(image)
if image != nil {
if imageView != nil {
imageView!.image = image!
}
}
}
}
}
}
}
Use Like this :
// Here imgPicture = your imageView and UIImage(named: "placeholder") is Display image brfore download actual image.
imgPicture.image = nil
NKPlaceholderImage(image: UIImage(named: "placeholder"), imageView: imgPicture, imgUrl: "Put Here your server image Url Sting") { (image) in }

How to return a array of names in uicollectionview cells swift 4

I am trying to insert an array of names into each of the cells as a test, but I keep getting an error when i type Example.name.text ECT. How do I return the array of names for each cell to have a name in it? Does the same work for images? My goal is to return UIImage so that each cell contains the next image in the UIImages.
class TestPage: UIViewController, UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
var collectView: UICollectionView!
var cellId = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout =
UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0,
right: 0)
layout.itemSize = CGSize(width: view.frame.width, height: 80)
collectView = UICollectionView(frame: self.view.frame,
collectionViewLayout: layout)
collectView.dataSource = self
collectView.delegate = self
collectView.register(Example.self, forCellWithReuseIdentifier:
cellId)
collectView.showsVerticalScrollIndicator = false
collectView.backgroundColor = UIColor.white
self.view.addSubview(collectView)
}
let listOfNames = ["John", "Smith", "Doe"]
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return listOfNames.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt
indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectView.dequeueReusableCell(withReuseIdentifier:
cellId, for: indexPath) as! Example
return cell
}
}
class Example: UICollectionViewCell {
let name: UILabel = {
let lb = UILabel()
lb.text = "This is a test"
lb.translatesAutoresizingMaskIntoConstraints = false
return lb
}()
// let aMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "Amajorscale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
// let bMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "bmajorscale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
//
// let cMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "c-major-scale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
//
// let dMajorScale: UIImageView = {
// let imgV = UIImageView()
// imgV.image = UIImage(named: "d-major-scale")
// imgV.contentMode = .scaleToFill
// imgV.translatesAutoresizingMaskIntoConstraints = false
// return imgV
// }()
//
override init(frame: CGRect) {
super.init(frame: frame)
addViews()
}
func addViews(){
addSubview(name)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat:
"H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views:
["v0" : name]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat:
"V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: [ .
"v0" : name]))
}

UICollectionView - Horizontal AutoScroll with Timer

I am using Horizontal Auto Scroll using timer. I want it to scroll one by one.
In my case it is scrolling continuos from left to right. and in last it also scroll white space after last cell.
#interface AccountsVC ()<UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
CGFloat width_Cell;
NSTimer *autoScrollTimer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
width_Cell = 0.0;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self configAutoscrollTimer];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[self deconfigAutoscrollTimer];
}
- (void)configAutoscrollTimer
{
autoScrollTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
}
- (void)deconfigAutoscrollTimer
{
[autoScrollTimer invalidate];
autoScrollTimer = nil;
}
- (void)onTimer
{
[self autoScrollView];
}
- (void)autoScrollView
{
CGPoint initailPoint = CGPointMake(width_Cell, 0);
if (CGPointEqualToPoint(initailPoint, self.collectionView.contentOffset))
{
if (width_Cell < self.collectionView.contentSize.width)
{
width_Cell += 0.5;
}else
{
width_Cell = -self.view.frame.size.width;
}
CGPoint offsetPoint = CGPointMake(width_Cell, 0);
self.collectionView.contentOffset = offsetPoint;
}else
{
width_Cell = self.collectionView.contentOffset.x;
}
}
In the custom class of your collectionViewCell:
self.contentView.frame = self.bounds;
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
and remove any other width calculations.
I am using like this
declare variable
var timer:Timer!
call from viewDidLoad
self.addTimer()
func addTimer() {
let timer1 = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.nextPage), userInfo: nil, repeats: true)
RunLoop.main.add(timer1, forMode: RunLoopMode.commonModes)
self.timer = timer1
}
func resetIndexPath() -> IndexPath {
let currentIndexPath = self.collectionView.indexPathsForVisibleItems.last
let currentIndexPathReset = IndexPath(item: (currentIndexPath?.item)!, section: 0)
self.collectionView.scrollToItem(at: currentIndexPathReset, at: UICollectionViewScrollPosition.left, animated: true)
return currentIndexPath!
}
func removeTimer() {
if self.timer != nil {
self.timer.invalidate()
}
self.timer = nil
}
func nextPage() {
let currentIndexPathReset:IndexPath = self.resetIndexPath()
var nextItem = currentIndexPathReset.item + 1
let nextSection = currentIndexPathReset.section
if nextItem == productImage.count{
nextItem = 0
}
var nextIndexPath = IndexPath(item: nextItem, section: nextSection)
if nextItem == 0 {
self.collectionView.scrollToItem(at: nextIndexPath, at: UICollectionViewScrollPosition.left, animated: false)
}
self.collectionView.scrollToItem(at: nextIndexPath, at: UICollectionViewScrollPosition.left, animated: true)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.addTimer()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.removeTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = collectionView.contentOffset
visibleRect.size = collectionView.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
let visibleIndexPath: IndexPath? = collectionView.indexPathForItem(at: visiblePoint)
pageControlView.currentPage = (visibleIndexPath?.row)!
}

drag and drop uiimage into another uiimageview

I am using following code snippet to drag and drop uiimageview
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[myImageView addGestureRecognizer:panRecognizer];
-(void)move:(id)sender {
CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
firstX = [myImageView center].x;
firstY = [myImageView center].y;
}
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[myImageView setCenter:translatedPoint];
}
This code is drags the whole myImageView ,but my requirement is to just drag the uiimage and drop it into another uiimagview.myImageView should stay as it is after dragging also.just I need to drag the myImageView layer.draggable image should be transparent. Any ideas would b appreciated.
I have put little effort to achieve your output. try it
Step 1 :Define this 3 Variables in your .h file
UIImageView *ivSource1, *ivDestination2, *tempIV;
Step 2 : Initialize all the three UIImageView and add to your ViewController write it in viewDidLoad method
ivSource1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"1.jpg"]];
[ivSource1 setFrame:CGRectMake(100, 100, 100, 100)];
[ivSource1 setTag:100];
[ivSource1 setUserInteractionEnabled:YES];
[self.view addSubview:ivSource1];
ivDestination2 = [[UIImageView alloc] init];
[ivDestination2 setFrame:CGRectMake(200, 300, 100, 100)];
[ivDestination2 setTag:101];
[ivDestination2 setUserInteractionEnabled:YES];
[self.view addSubview:ivDestination2];
tempIV = [[UIImageView alloc] init];
[tempIV setFrame:CGRectMake(0, 300, 100, 100)];
[tempIV setTag:102];
[tempIV setUserInteractionEnabled:YES];
[self.view addSubview:tempIV];
Step 3 : Define following touch methods to handle movement of image for Drag & Drop
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if([[touch view] tag] == 100)
{
[tempIV setImage:ivSource1.image];
[tempIV setCenter:[touch locationInView:self.view]];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[tempIV setCenter:[touch locationInView:self.view]];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
[tempIV setCenter:[touch locationInView:self.view]];
if(CGRectContainsPoint(ivDestination2.frame, [touch locationInView:self.view]))
{
[ivDestination2 setImage:tempIV.image];
}
// Remove image from dragable view
[tempIV setImage:[UIImage imageNamed:#""]];
}
With iOS 13, you can use Drag & Drop and copy/paste APIs in order to perform a drag and drop operation of a UIImage from one UIImageView to another UIImageView. According to your needs, you may choose one of the two following Swift 5.1 implementations.
#1. Using UIDragInteraction, UIDragInteractionDelegate and UIPasteConfiguration
import UIKit
class ViewController: UIViewController {
let imageView1 = UIImageView()
let imageView2 = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
imageView1.image = UIImage(named: "image")
imageView1.contentMode = .scaleAspectFit
imageView1.isUserInteractionEnabled = true
let dragInteraction = UIDragInteraction(delegate: self)
dragInteraction.isEnabled = true
imageView1.addInteraction(dragInteraction)
imageView2.contentMode = .scaleAspectFit
imageView2.isUserInteractionEnabled = true
let configuration = UIPasteConfiguration(forAccepting: UIImage.self)
imageView2.pasteConfiguration = configuration
let stackView = UIStackView(arrangedSubviews: [imageView1, imageView2])
view.addSubview(stackView)
stackView.distribution = .fillEqually
stackView.frame = view.bounds
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
override func paste(itemProviders: [NSItemProvider]) {
_ = itemProviders.first?.loadObject(ofClass: UIImage.self, completionHandler: { (image: NSItemProviderReading?, error: Error?) in
DispatchQueue.main.async {
self.imageView2.image = image as? UIImage
}
})
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
guard let image = imageView1.image else { return [] }
let item = UIDragItem(itemProvider: NSItemProvider(object: image))
return [item]
}
}
#2. Using UIDragInteraction, UIDragInteractionDelegate, UIDropInteraction and UIDropInteractionDelegate
import UIKit
class ViewController: UIViewController {
let imageView1 = UIImageView()
let imageView2 = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
imageView1.image = UIImage(named: "image")
imageView1.contentMode = .scaleAspectFit
imageView1.isUserInteractionEnabled = true
imageView2.contentMode = .scaleAspectFit
imageView2.isUserInteractionEnabled = true
let dragInteraction = UIDragInteraction(delegate: self)
dragInteraction.isEnabled = true
imageView1.addInteraction(dragInteraction)
let dropInteraction = UIDropInteraction(delegate: self)
imageView2.addInteraction(dropInteraction)
let stackView = UIStackView(arrangedSubviews: [imageView1, imageView2])
view.addSubview(stackView)
stackView.distribution = .fillEqually
stackView.frame = view.bounds
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
extension ViewController: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
guard let image = imageView1.image else { return [] }
let item = UIDragItem(itemProvider: NSItemProvider(object: image))
item.localObject = image
return [item]
}
}
extension ViewController: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: UIImage.self) && session.items.count == 1
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
let dropLocation = session.location(in: view)
let operation: UIDropOperation
if imageView2.frame.contains(dropLocation) {
operation = session.localDragSession == nil ? .copy : .move
} else {
operation = .cancel
}
return UIDropProposal(operation: operation)
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
session.loadObjects(ofClass: UIImage.self) { imageItems in
guard let images = imageItems as? [UIImage] else { return }
self.imageView2.image = images.first
}
}
}

How to access hyperlinks in PDF documents in iphone/ipad?

How can I access hyperlinks in PDF documents on the iPhone and iPad?
I want to set links on the content of an e-book.
Use following function to put UIButtons on the links in PDF. This will draw Buttons on your UIView. You have to pass your page as parameter. Currently it will draw button with type UIButtonTypeRoundedRect you change afterwards it to custom so it will be hidden. Initially buttons may be drawn other place than link so you need to adjust x/y position according to you requirement.
-(void)drawLinks:(CGPDFPageRef)thisPage
{
CGPDFDictionaryRef pageDictionary = CGPDFPageGetDictionary(thisPage);
CGPDFArrayRef outputArray;
if(!CGPDFDictionaryGetArray(pageDictionary,"Annots", &outputArray))
{
return;
}
int arrayCount = CGPDFArrayGetCount( outputArray );
if(!arrayCount)
{
//continue;
}
for( int j = 0; j < arrayCount; ++j )
{
CGPDFObjectRef aDictObj;
if(!CGPDFArrayGetObject(outputArray, j, &aDictObj))
{
return;
}
CGPDFDictionaryRef annotDict;
if(!CGPDFObjectGetValue(aDictObj, kCGPDFObjectTypeDictionary, &annotDict)) {
return;
}
CGPDFDictionaryRef aDict;
if(!CGPDFDictionaryGetDictionary(annotDict, "A", &aDict)) {
return;
}
CGPDFStringRef uriStringRef;
if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) {
return;
}
CGPDFArrayRef rectArray;
if(!CGPDFDictionaryGetArray(annotDict, "Rect", &rectArray)) {
return;
}
int arrayCount = CGPDFArrayGetCount( rectArray );
CGPDFReal coords[4];
for( int k = 0; k < arrayCount; ++k ) {
CGPDFObjectRef rectObj;
if(!CGPDFArrayGetObject(rectArray, k, &rectObj)) {
return;
}
CGPDFReal coord;
if(!CGPDFObjectGetValue(rectObj, kCGPDFObjectTypeReal, &coord)) {
return;
}
coords[k] = coord;
}
char *uriString = (char *)CGPDFStringGetBytePtr(uriStringRef);
NSString *uri = [NSString stringWithCString:uriString encoding:NSUTF8StringEncoding];
CGRect rect = CGRectMake(coords[0],coords[1],coords[2],coords[3]);
CGPDFInteger pageRotate = 0;
CGPDFDictionaryGetInteger( pageDictionary, "Rotate", &pageRotate );
CGRect pageRect = CGRectIntegral( CGPDFPageGetBoxRect( thisPage, kCGPDFMediaBox ));
if( pageRotate == 90 || pageRotate == 270 )
{
CGFloat temp = pageRect.size.width;
pageRect.size.width = pageRect.size.height;
pageRect.size.height = temp;
}
rect.size.width -= rect.origin.x;
rect.size.height -= rect.origin.y;
CGAffineTransform trans = CGAffineTransformIdentity;
trans = CGAffineTransformTranslate(trans, 0, pageRect.size.height);
trans = CGAffineTransformScale(trans, 1.0, -1.0);
rect = CGRectApplyAffineTransform(rect, trans);
UIButton *btnTmp = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // After testing put here UIButtonTypeCustom
[btnTmp addTarget:self action:#selector(urlOpen:) forControlEvents:UIControlEventTouchUpInside];
rect.origin.x = rect.origin.x + 78; //I have adjusted this as per my requirement
rect.origin.y = rect.origin.y + 108; // I have adjusted this as per my requirement
btnTmp.frame = rect;
btnTmp.titleLabel.text = uri;
[self.superview addSubview:btnTmp];
}
}