Posts

Showing posts from 2020

Rect size for image size based image iOS Objective C

 Solution: - ( CGRect ) contentClippingRect :( U IImageView  *)img {    CGRect  imageRect;    CGFloat  scaleX = img. bounds . size . width /img. imag e . size . width ;    CGFloat  scaleY = img. bounds . size . height /img. ima ge . size . height ;    if (scaleX < scaleY) {     imageRect =  CGRectMake ( 0 , (img. bounds . size . height  - scaleX*img. image . size . he ight )* 0.5f , img. bounds . size . width , scaleX*img. image . size . he ight );   }  else  {     imageRect =  CGRectMake ((img. bounds . size . wi dth -scaleY*img. image . siz e . width )* 0.5 ,  0 , scaleY*img. image . size . wi dth , aspectRatioX*img. image . size . he ight );   }       return  imageRect;   }

Rect size for image size based imageView iOS swift

 Solution: extension   UIImageView  {       var   contentClippRect :  CGRect  {      var  imageRect: CGRect !      let   scaleX  =  bounds . size . width/image !. size . width      let   scale Y =  bounds . size . height/image !. size . height      if   scaleX   <   scale Y  {       imageRect =  CGRect (x:  0 , y: ( bounds . size . height   -   scaleX *image !. size . heigh t ) * 0.5 , width:  bounds . size . width , height:  scaleX *image !. size . heigh t )     }      else  {       imageRect =  CGRect (x:( bounds . size . width- scale Y *image !. size . width ) * 0.5 , y: 0 , width:  scale Y *image !. size . width , height:  scaleX *image !. siz e . height )   }      return  im...

Remove the layer from its superLayer iOS objective C

Solution: Right: for ( int  i= 0 ;i< self . layer . sublayers . cou nt ;i++) {      CALayer  *item  =  self . layer . sublayers [i];      if ([item. name    isEqual :  @"myLayer" ]) {       [item  removeFromSuperlayer ];       i--;     }   } Wrong:   for(CALayer *item in self.layer.sublayers) {     if([ item.name   isEqual: @" myLayer "]) {       [item removeFromSuperlayer];     }   }

Convert cgpath from superView to subVIew iOS swift

Problem: I had a view with cgpath and i want to convert the to its subview with the same position.I had used the below code to achieve that  Solution: CGAffineTransform translation =  CGAffineTransformMakeTranslati on (- View . frame . origin . x , - View . frame . origin . y ; CGPathRef  movedPath =  CGPathCreateCopyByTransforming Path ( Path ,& translation); View . Path  = movedPath;

Create image with tint colour in iOS objective C

 Solution: You cannot set the background color of an image directly.Use the below method to set the background colour of an image with red colour as like below.. UIImage * newImage = [[ UIImage alloc ] init]; UIGraphicsBeginImageContextWit hOptions(newImage.size, NO, newImage.scale);       UIColor *col = [UIColor redcolor];       [col set];       [newImage drawInRect:CGRectMake(0, 0, newImage.size.width, newImage.size.height)];       newImage = UIGraphicsGetImageFromCurrentI mageContext();       UIGraphicsEndImageContext();

Enumeration example in objective C

Solution:  You can use the below function for enumeration. typedef   enum  value_type {   type1,   type2,   type3,   type4, }type;

Complementry color for any color iOS swift

 Solution: You can use this extension for getting the complementary colour for any colours in iOS swift. extension UIColor { var compColor: UIColor {                  let ciColor = CIColor(color: self)                  let compRed: CGFloat = 1.0 - ciColor.red         let compGreen: CGFloat = 1.0 - ciColor.green         let compBlue: CGFloat = 1.0 - ciColor.blue                  return UIColor(red: compRed, green: compGreen, blue: compBlue, alpha: ciColor.alpha)     } }

Save and retrieve boolean value in Userdefaults objective C

 Solution:    If you save the boolean value in swift and retrieve in objective C then retrieve as String and convert as boolean.        NSString  *isOn = [defaults  objectForKey : @" isOn " ];               if (isOn. boolValue  ==  YES  || isOn ==  nil ) { }

iOS there is a way to combined switch cases in objective C

 Solution: You can use two cases in one objective C as like below. case 8: case 9: //enter the codes below

cgpathref displays error inside switch case objective C

 Problem: When i try to add switch case in cgpath function displays below error code. cgpathref expression expected objective c for switch case. Solution: In some cases objective C does not allow some set of codes inside the switch case.So better avoid those codes inside switch and add outside of the switch case.

Scale the CGPath in objective C

 Solution: The below code is used to scale the path in objective C.      CGAffineTransform  transform =  CGAffineTransformMakeScale ( 1 ,1 );      CGPathRef  intermediatePath =  CGPathCreateCopyByTransforming Path ( path , &transform);

XCode compile failed when install new pod iOS swift

 Problem: I had installed new pods in my project.After that when i try to compile my code it shows error in import module something different.But i don't had any issues in my pod. I had tried to clean the derived data and cleaned my project also it didn't work. Solution: Select pod in left side target.In build settings check build architecture as standard architecture armv7. Select all the pods and change their architecture save and clean the project and rebuild it.  

Xcode shows exclamatory symbol in signing identity but i had added all certificates into keychain

 Solution: Sometimes XCode shows like that.You have to restart the xcode and try that it will works. But if you had not a valid certificates in your machine then it's your problem to solve.Must check the validity of certificates in the machine and download it correctly.

iOS app EKalarm proximity not works || Location based EKAlarm not worrks for an event

 Solution: In event creation and handling if you are needed time based alarms then create an event and add EKAlarm with that event with recurrence rule also. If you are going with location based alarms then must use EKReminder in EKEvent.First create an EKReminder then create one CLLocation after that add the location to that reminder with three options.     1.while arriving     2.While leaving     3.None Before add the reminder must have to check that event with type not .event it's .Reminder After that open the reminder pp and check it was added or not.

Get the degree angle from View iOS swift || Drawn object degree angle calculation iOS

 Solution: The below method is used to calculate the degree from the drawn object.        let  radians =  atan2f ( Float (view! . transform . b ),  Float (view! . transform . a ))        var  degrees = radians  *   Float ( 180   /   Double . pi )        degrees = degrees  >=   0  ?  abs (degrees) :  360   +  degrees

Create compose mail when click button iOS swift

Solution:              let  receivers = event. receivers   !=   nil  ? [ receivers ] : []                           let  mailComposerVC =  MFMailComposeViewController ()             mailComposerVC. mailComposeDele gate  =  self     // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property                          mailComposerVC. setToRecipients (receivers  as ?  NSArray   as ? [ String ])             mailComposerVC. setSubject (  "" )             mailComposerVC. setMessageBody ( "" , isHTML:  false )              self . viewControl . present ( mailComposerVC, ...

Call action implementation iOS swift || Call implementation || phone number call iOS swift || Phone call implementation when click the number iOS swift

Problem: I want to create a button with title of phone number and if the user touches the button it wants to call that phone number. Solution: Just add the below code inside the action of that button and pass the number value. Code:   let  cleanNumber = number. replacingOccurrences ( of:  "[^0-9+]" , with:  "" , options:  NSString . CompareOptions . regula rExpression , range: nil );              if   let  url =  URL (string:  "TEL:// \( String (describing: cleanNumber)) " ) {                  UIApplication . shared . open (url, options: [:], completionHandler:  nil )             }

App crashes when i use nsmutablestring iOS swift

   Solution: @property  ( nonatomic ,  assign )  NSMutableString *  str ; When i use the above line try to run the app it crashes. Because it's a mutable value..  NSMutableString and  NSString are came from nsobject with mutble value.. @property  ( nonatomic ,  weak )  NSMutableString *  str ; You must have to use like above the app will works fine..You cannot be able to assign a value to the mutated objects.You must use that as weak property.. Happy coding...

Reverse for loop in iOS objective C and swift || For loop in descending order

 Solution: Swift: for  i  in  ( 0 ..<array . count ). reversed () { //your code here } Objective C:              for ( int  i =  array . count - 1 ; i >=  0 ; i--){ //your code here } If you want to reverse your array and find the last nearby updated value then use the above method. It will also called as  stack  last in first out.

EKAlarm not works for Event || Alarm added but not triggered to an event iOS swift

   Solution: EKAlarm had different methodology to handle.If you had an event with start date and end date and your event wants to trigger an alarm at the time of event start then you don't have to give the absolute date to the event. If your event wants to trigger an alarm before the event start then you can give the absolute date and time.Then only it will works.If you set an alarm date with same time of an event then it will never trigger an alarm.So carefully update that.            alarm.absoluteDate = e.startDate //avoid this line when event start time and alarm time as same

Create audio player with button icon change in tableview or collectionVIew in iOS swift

   Problem: I want to create an tableview with audio player.If the user taps inside the tableview button it will change the icon of the button and user can able to play and pause the audio. Solution: In tableview cell add the button with its target.Also set the button title and title image for both normal and selected state. Inside the target if button is selected then change the state of the button and play the player. If button is unselected then pause the player or stop the player. If you had different targets for cell then must be use remove the other target's after that add the target that you want to apply. Also want to implement the willdisappear method must be handle to stop the player and change the state of the button. For the above you want to set the tag to the button and access the cell using the tag. If the player reached the endtime of the audio then the delegate method will be called "Didfinishplaying". Inside that you can change the state of the button an...

Take screenshot in simulator iOS

 Solution: You can take screenshot from your simulator..Open the simulator and press cmd+s Then screenshot was taken. OR You can click on menu click on menu file save then screenshot taken..

CAShapeLayer beizerpath edges not smooth objective c iOS

 Problem: ShapeLayer edges are not smooth while drawing in CAShapeLayer. Solution:   [shape  setLineCap : kCALineCapRound ]; Add the above line it will smooth the layer in the edges.

leadingSwipeActionsConfigurationForRowAt crashes iOS swift

 Problem:      func   tableView ( _  tableView:  UITableView , leadingSwipeActionsConfigurati onForRowAt indexPath:  IndexPath ) ->  UISwipeActionsConfiguration ? { } While using the above funtion left to right swipe while in editing when try to swipe another time app crashed. Solution: While your tableView is in editing if you tried one more time for swipe it will conflict with the previous number of rows.So it will  be crash. Try to add the line with         if   ! tableView. isEditing  { } then only proceed with your editing otherwise ignore it..The problem  will be solved  

UITapGestureRecognizer not works iOS swift

 Solution:   let  tapGesture =  UITapGestureRecognizer (target:  self , action:  #selector (gesture Tap ( _ :)))   tapGesture. numberOfTapsReq uired  =  1   cell. img . addGestu reRecognizer (tapGesture) If you added two recognizer methods to a imageview then only one tapgesture will works. So must add only one tapgesture to a view.Then only it will works.

Seperate phone number with country code iOS swift || Get only the phone number from iOS swift || How to remove country code while Pick Phone Number from contacts

 Solution:      The below function will return the phone number if you given with country code and + symbol.Its a default method in iOS. If you had the phone number with different countries with country code and other formate just pass it as string to the below function and get the original phone number.You don't need any pod files to get that.It's a default method in iOS.  Before you start the function must import the  PhoneNumberKit module to your project. Code: import  PhoneNumberKit func phoneNumberParse(phoneNo:String) -> String { var phNo:String: "" let  phoneNumberKit =  PhoneNumberKit ()        do  {            let  phoneNumber =  try  phoneNumberKit. parse (phoneNo)         phNo  = String(describing:phoneNumber. nationalNumber )       }        catch  { } return phNo }

Mac unable to install the package of the software downloaded from chrome

Image
 Solution: 1.First open the package it shows unable to install. 2.Open system preference app in your mac or goto apple logo in top of the menu and select preference -> open security and privacy 3. 4. select click the lock to make changes. 5.Enter password to unlock 6.In allow apps downloaded from that show your software name and says open it anyway..click on that and install. .

How to log an cgaffaintransform in objective C

 Solution: You cannot directly log the cgaffaintransform for that you can convert the CGAffaintransform into strin and log into that.      NSLog ( @"state = %@" , NSStringFromCGAffineTransf orm ( Object . tr ansform ));  

How to get the label value from contacts using phone number || cnlabel get string swift || CNContact get the name label and name

 Solution:    Below you can find the label and name from the phone number.        for  cont  in  place. phoneNumbers         {            let  replaced = cont. value . stringValue . replaci ngOccurrences (of:  "[^0-9+]" , with:  "" , options:  NSString . CompareOptions . regula rExpression , range: nil )            if  replaced  ==  my phoneNumber                     {                        let  localizedLabel =  CNLabeledValue < NSString >. local izedString (forLabel: cont. label !)                        let  PhoneLabel  = localizedLabel                        ...

CollectionView SwipecollectionCell after edit collectionView not resigned

 Solution: Before you have to call the below method don't reload the cell.  func   hideSwipeCollectionViewCells () {        print ( CollView . indexP athsForSelectedItems )          for  cell  in   workSpaceCollView . visibleCells  {              if   let  cell = cell  as ?  SwipeCollectionViewCell  {                 cell. hideSwipe (animated:  false )             }         }     }

Common tableView cell for more rows display crash while using different cell iOS swift

 Solution: If you are using different cells for a particular section then must return every section with cell.Because if you are using two section with one common cell and another two sections with another cell then declare it in every section with cell and return it.Don't use in common cell for few cells.Because iOS not allow you to reuse more cells in particular section.Only one cell to be returned for every section.

Cannot add something to an array swift

 Problem: I want add some values to an array iOS swift.Not able to add in that. Solution: It's not possible to add values in an array.You can assign values to an array is possible. In NSMutableArray only you can add values in that dynamically. var value:NSArray! value.addObject(some value).    ////not possible var value:NSMutableArray! value.addObject(some value).    ////possible

How the reset works coredata iOS swift

 Solution: Reset the last changed context will be available If you saved the context then it will not be available.So if you want to reset then before save try that to reset.

Cell button action not works instead of that cell didselect row calls swift || collection View button action not works instead of that cell didselect row calls swift || didselect called while tapping button in collectionview swift

Problem: I had a cell with button and some set of views.I added the target to that button.If i clicked that button target calls and also the cell didselect row calls. How to disable the didselect call in button click action. Solution: If you added the target then didselect also will be called.So you must avoid add target to a button in a cell.Instead of you can add the tap gesture to the button and call the action.It will avoid to call didselect method.                    let  singleTap =  UITapGestureRecognizer (target:  self , action: #selector ( self . didTapAction ( _ :)))                   singleTap. numberOfTapsRequired  =  1                   Cell. Btn . addGest ureRecognizer (singleTap)

Delete a drawn CGPoint in a View iOS swift || Delete CGPoint in an imageVIew

  Solution : You cannot remove the points from the view.Instead of that you can redraw or re-initialize the view. You cannot be delete the drawn image in that.Because it was set as like image view background.So you cannot be clear.You must be re initiate it.

Convert some value to CGPoint objective C

Solution: CGPoint value = [points[0] CGPointValue];

Get CGPoints from CGMutablePath || Find min and max values from CGMutablePath || iOS find MINX,MINY,MAXX,MAXY from CGMutablePath

Solution: let value = path.getPathElementsPoints() let xArray = value.map(\.x) let yArray = value.map(\.y) let minX = xArray.min()!-drawingPenRectAdj let maxX = xArray.max()!+drawingPenRectAdj let minY = yArray.min()!-drawingPenRectAdj let maxY = yArray.max()!+drawingPenRectAdj print("min x",minX) print("max x",maxX) print("min y",minY) print("max y",maxY) let points = NSMutableArray() points.add(CGPoint(x: minX, y: minY)) points.add(CGPoint(x: maxX, y: maxY)) var covertPoints:[CGPoint] = [] var cgpath:CGMutablePath! = CGMutablePath.init() for i in 0..

print CGRect objective c

Problem: Want to print the cgrect of a button in iOS objective C. Solution: NSLog(@"close button frame = %d",NSStringFromCGRect(self.RectView.Button.frame));

Get the updated objects in coredata for rollback

Solution:          print ( appdel . getContext (). up datedObjects ) It will display the updated objects that are changed after the last commit.If you are tried with 

Rollback is not working for coreData entities

Solution: You could simply refetch the coredata entities for unsaved changes. But you can restart the app the unsaved changes will be discarded.So you must have to save the changes. But you changed in persistant store with current context then the changes will be available in before saving.You can try the rollback context to discard the last changes. Also undomanager available in coredata.You could try that to start the changes and rollback to the particular point....

rollback() not works coredata

Solution: In coredata if you tried rollback then the current context will be rolled back.But if you tried with global context it will never works.So you have try that in cancel you will rollback after comeback to that screen you have to do another rollback in viewDidload. Then it will works good

CollectionVIew size for item not sets for zero.It displays wrong size swift || sizeForItemAt return 0 but cell came || UICollectionView sizeForItemAt Called But Not Sized Correctly

Problem: I had tried to set the size for item zero but it not sets properly.For that it returns sized value. collection View(_: layout: size For Item At:)              let  newSize =  my Array . count   >   0  ?  CGSize (width: width / 3 , height: width / 3 ) :  CGSize (width:  0 , height:  0 ) return  newSize Solution: Because in apple they already said that you must have to set the size value to be non zero.              let  newSize =  my Array . count   >   0  ?  CGSize (width: width / 3 , height: width / 3 ) :  CGSize (width:  0.5 , height:  0.5 ) return  newSize Use the above code it will works good.