Introduction
The DMSegmentedControl is a custom segmented control for iOS developed by Deepak Mittal. It allows you to create customizable segmented controls with various styling options.
Installation
- Install via Cocoapods by adding the following line to your Podfile:
- Run the command
pod install
in your terminal. - Import the DMSegmentedControl module in your code:
pod 'DMSegmentedControl'
import DMSegmentedControl
Usage
To use DMSegegatedControl, follow the steps below:
Creating a Segmented Control
To create a segmented control, use the following code:
// Initialize the segmented control
let segmentedControl = DMSegmentedControl(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
// Set the segmented control titles
segmentedControl.sectionTitles = ["Title 1", "Title 2", "Title 3"]
// Customize segmented control appearance
segmentedControl.segmentEdgeInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
segmentedControl.selectionStyle = .box
segmentedControl.backgroundColor = UIColor.lightGray
// Add segmented control as a subview
self.view.addSubview(segmentedControl)
Responding to Selection
You can respond to the segment selection by implementing the following method:
segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged), for: .valueChanged)
@objc func segmentedControlValueChanged() {
let selectedSegmentIndex = segmentedControl.selectedSegmentIndex
// Perform actions based on the selected segment index
}
Customization
The DMSegegatedControl provides various customization options:
Segment Titles
To set the titles for each segment, use the sectionTitles
property:
segmentedControl.sectionTitles = ["Title 1", "Title 2", "Title 3"]
Segment Appearance
You can customize the appearance of each segment using the following properties:
segmentEdgeInset: UIEdgeInsets
– Sets the edge insets for each segment.segmentWidth: CGFloat
– Sets the width of each segment.segmentContentColor: UIColor
– Sets the color of the segment content.
Selection Style
To change the selection style, use the selectionStyle
property. Available styles are:
box
– Selection appears as a colored box.textWidthStripe
– Selection appears as a stripe extending the width of the segment text.
Selection Indicator Color
You can change the color of the selection indicator using the selectionIndicatorColor
property:
segmentedControl.selectionIndicatorColor = UIColor.red
Delegate Methods
You can implement the delegate methods to perform actions for specific events. The available delegate methods are:
dmSegmentedControl(_ segmentedControl: DMSegmentedControl, didSelectSegmentAtIndex index: Int)
– Called when a segment is selected.
Conclusion
DMSegmentedControl provides a flexible and customizable way to implement segmented controls in your iOS app. By using the provided customizations, you can create segmented controls that match your app’s design aesthetics.