#Coding

How to resize an Image of UIButton in Swift?

by

Sometime there may be need to resize the image displayed in UIButton for not availability of proper sized image because of some reason. Wrong size gives unwanted results like stretched out image pixels etc. In this post we are assuming simple UIButton with image only.

First solution:

We can update contentMode settings of imageView property of UIButton. Default value is .scaleToFill. It scales the image to fill the UIButton ignoring aspect ratio.


btn.imageView?.contentMode = .scaleAspectFit

This will solve the 50% of problem because UIButton will render the image maintaining the aspect ratio.

Now if in worst case scenario problem isn’t solved because of bigger dimension of image then we have second solution:

CONTINUE READING

How To Scroll UICollectionView To End Of Footer or Header

by

Recently someone brought me a problem that needed my perspective. A vertical UICollectionView is using sections for displaying items. Requirement is to scroll to bottom of UICollectionView. A method that can be used used for scrolling to last item in UICollectionView is

scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionView.ScrollPosition, animated: Bool)
Scrolls the collection view contents until the specified item is visible.

This method worked incomplete. It made collection view to last item. Isn’t that what is required? There is a custom footer at the end of section and footer needs to be visible. It did not scroll to last footer but stopped just before footer.

To find the information regarding offset on our footer view we will gather layout information for that particular supplementary view. Remember supplementary view can be either header or footer so this works for both. Here is an extension to UICollectionView

CONTINUE READING

iOS UIKit Animation Equivalent in Android's Kotlin Animation

by

Animation is a common feature we use often in our apps. iOS SDK does provide different ways to implement. From higher-level UIKit methods to more lower Core Animation. Any UIKit based animation is internally translated into core animations. UIKit methods abstracts the layer of core animation.

Today here we will see the higher-level UIKit animation’s equivalent in Android’s Kotlin - one of the ways that Android SDK provides us. We will use ViewPropertyAnimator - a simplified and optimised way to animate properties of a View in Android. A simple example to rotate a view by certain angle for a duration and also callback implementation when animation ends.

Below is the equivalent code snippet for Android Animation in Kotlin and iOS animation on views with UIKit.

CONTINUE READING

How to Present a View Modally From UITabBarController in Swift

by

Each tab of a tab bar controller is associated with a view controller. When the user selects a specific tab, the tab bar controller displays the root view of the corresponding view controller, replacing any previous views. The tab bar interface displays tabs at the bottom for selecting between the different display views.

Tab bar controller lets us to implement easy multi-selection of displays easily. In this user interface style tabs at the bottom remains visible. Display switches between selection at child controller section above.

Comes a situation where view controller associated with a specific tab to display modally or push where Tabs at bottom gets covered behind this view controller. Instagram app is a good example where when create-post-tab is pressed, then display is opened over the tab controller.

How to present UITabBarItem’s view controller modally?

CONTINUE READING

How to Disconnect CoreBluetooth Peripheral cleanly in Swift

by

To disconnect a connected peripheral in CoreBluetooth we call method cancelPeripheralConnection


centralManager.cancelPeripheralConnection(peripheral)

This did disconnect peripheral in CoreBluetooth. In my program there is code that caches old discovered peripherals for certain period. It does go through cached peripherals to search for their services. What I found was that even if peripheral was disconnected code was somehow discovering the services and characteristics. There is a segment of code which is written to trigger certain behaviour when characteristics of peripheral is discovered. I did not want this for disconnected peripherals. Problem is not an issue for there are very simple solution for this scenario like checking the state of peripherals before trigger and etc.

I am emphasizing that Disconnected peripheral’s services still can be discovered in CoreBluetooth. Which is not an issue. I had assumed that when peripheral gets disconnected it removes its services and characteristics.

These methods do get called up even if peripheral is no more connected.


func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)
CONTINUE READING

How to detect click inside StaticBody2D in Godot Game Engine?

by

A simple approach to detect mouse click in our game is to intercept input event in in-built _input method. Let’s intercept the input.


extends StaticBody2D
func _input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT and event.pressed:
            print(“A click!”)

The problem is that input detection is registered all over the viewport. Let me explain. I have a Sprite child node inside StaticBody2D node. My intention is to detect mouse input over the visible sprite only. In our 2D game we may want to select an object in our world with mouse and do some interaction with it. In this case mouse input is been registered outside the Sprite node.Note that our script is attached to StaticBody2D. As a result this node has to have a shape, so the example has a collision shape as a child. We are trying to keep Sprite node loosely coupled from the logic. Documentation clearly says that StaticBody2D is not intended to move. This makes perfect for objects like trees in the game.

Let’s come back to our problem. My assumption for the behaviour would be that StaticBody2D is shapeless. Yes, we did add a collision shape so it mouse input should be triggered only over defined collision shape. However, StaticBody2D is behaving shapeless and mouse input is registered all over the screen.


A simple approach I discovered is two steps.

CONTINUE READING

How to Set and Restrict the Camera 2d Boundary in Godot Game engine

by

I have been learning and practicing Godot game engine by watching free high quality video series from HeartBeast. I really want you to go and watch this RPG tutorial series to learn practical fundamentals of Godot engine. In part-20 of the series we learned about setting up camera and make camera follow the player around the level. It is very easy in Godot.

Above tutorial video lets you learn to easily setup player Camera2D. One thing was missing and I took a challenge exercise where camera stops following the player when player is near the edge or boundary of the level. Currently camera moves with player and vast empty space is visible when player is near boundary of the level.

My solution is based on existing type of game world I am working with.

CONTINUE READING

How to Change Color of UISwitch in Off State

by

There is no given individual property available to change the color of UISwitch in “off” state. We have the property to change color for “on” state called onTintColor. For "off" sate We can achieve by changing certain combination of properties to UISwitch.

By default background color of UISwitch is clear. We change background color to new color. Remember this changes the background color of UISwitch, and this will result in rectangle solid background color. Our UISwitch must have rounded corners and to match that we update the corner radius of UISwitch. That is it.

Optional step is to update tintColor of UISwitch to match the background color to keep it even.

First way, Inheritence - creating custom UISwitch class. In this example code I am exposing designable property for easy use in our storyboard.


class CustomSwitch: UISwitch{
    @IBInspectable var offTintColor: UIColor? {
        didSet {
            let minSide = min(bounds.size.height, bounds.size.width)
            layer.cornerRadius = minSide / 2
            backgroundColor = offTintColor
            tintColor = offTintColor
        }
    }
}

CONTINUE READING

How To Optimize Laravel Code Eloquently With UpdateOrCreate()

by

In beginning of my Laravel learning, I did write more lines of code to perform my task than I write now. I started learning to adopt more eloquent ways of coding for Laravel encourages us to write. One simple task I performed by writing this many number of lines:


$place = PlaceModel::where('id', "132")->first();
if(isset($place))
{
  $place->update(['name' => 'Place Name', 'address' => 'Place Address',]);
}
else
{
  $place = PlaceModel::create([
    'name' => 'Place Name',
    'address' => 'Place Address',
  ]);
}

This many lines of code can be optimised to single statement of line in Laravel Eloquent way. This is ome of the ways to optimize eloquent query on Laravel:

CONTINUE READING

प्रोग्रामिंग: एक परिचय (An Introduction to Programming in Nepali)

by

यस ट्यूटोरियलको लक्ष्य छ तपाईंलाई सकेसम्म चाँडो त्यो चरणमा पुग्ने प्रयास गर्न जहाँ तपाईं उपयोगी प्रोग्रामहरू लेख्न सक्नुहुनेछ। नयाँ प्रोग्रामिंग भाषा सिक्ने एक मात्र तरिका यसमा प्रोग्रामहरू लेख्नु हो। तपाईले प्रोग्राम पाठ कहिँ लेख्न, यसलाई सफलतापूर्वक कम्पाइल गर्न, लोड गर्न, चलाउन, र आउटपुट फेला पार्न सक्षम हुनुपर्दछ।

मैले सरल कारणले गर्दा यो ट्यूटोरियल श्रृंखला को लागी जाभास्क्रिप्ट(javascript) भाषा छानिएको छु। जाभास्क्रिप्ट कोड सिक्न र गर्न सजिलो छ। यसले तपाईंको सिक्ने समयको बचत गर्न सक्दछ। जाभास्क्रिप्ट हरेक आधुनिक वेब ब्राउजरमा स्थापित हुन्छ, त्यसैले तपाईं अहिले जाभास्क्रिप्टमा प्रोग्रामिंग सुरु गर्न सक्नुहुनेछ उही ब्राउजरमा जुन तपाईं यो लेख पढ्न प्रयोग गर्दै हुनुहुन्छ। यदि तपाईं गुगल क्रोम प्रयोग गर्दै हुनुहुन्छ भने, केवल “view” मेनूमा जानुहोस्, “developer” उप-मेनूमा क्लिक गर्नुहोस्, र तपाईंले “javascript console” खोल्ने विकल्प देख्नुहुनेछ।

हामी यी आधारभूत कुरामा ध्यान दिनेछौं: भ्यारीएबल र constants, अंकगणित(arithmetic), control-flow र फंक्शन।

CONTINUE READING

Recommended posts