Swift: Best way to manage UI elements, such as UIButtons? [closed] - ios

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm new to Swift.
I'm trying to make template files for all elements that I often use such as buttons and labels.
Can you tell me the best way manage the templates like that has the appearance like including the colors, corner radius?
I cannot figure out except using Class files.
Thanks!

You have 2 ways to do it.
1 - create your own class
final class PrimaryButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.red
setTitleColor(UIColor.black, for: .normal)
}
}
2 - create extension to configure
extension UIButton {
func style() {
backgroundColor = R.color.primary()
setTitleColor(R.color.black(), for: .normal)
}
}
and call this function in viewDidLoad
first style is preferred

Personally, I like to create a new file called "Styling" with the same-named class.
Then, inside there, I create static functions that accept parameters that you want to edit (for example, button).
class Styling {
static func styleButton(_ button: UIButton) {
button.layer.cornerRadius = 25.0
}
}
Then I just call it by typing in vc:
Styling.styleButton(myButton)

To add to the above answers what works for me is putting series of buttons in an array of UIButtons. It makes it much simples to rearrange them while developing the app or adjusting to various screens.
Here is a simplified example of 12 buttons forming a colorful flag:
var flagButton: [UIButton] = []
for i in 0...11 {
flagButton.append(UIButton())
flagButton[i].frame = CGRect(x: x, y: y, width: width, height: height)
self.view.addSubview(flagButton[i])
}

You can create a class like this:
class CustomButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.layer.cornerRadius = 20
}
}
And use it:

Related

Is there any way to make a button do something on the first press and something else on the second press in Swift [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I was currently working on an app and have made it so when I press the continue button it shows the image with a .toggle() but on the second time p press it I want it to change to a blank screen is there any way to do this or am I going to have to add a second button to change to a blank canvas.
You can use state pattern here.
First create enum with all button states
enum ButtonState {
case notTapped, tappedOnce
}
Then create a property in a class that handle button tap
var buttonState: ButtonState = .notTapped
Now you can handle button tap in a way you want
#IBAction func buttonTapped(_ sender: Any) {
switch buttonState {
case .notTapped:
print("do something")
buttonState = .tappedOnce
case .tappedOnce:
print("do something again")
}
}
You can add any states you want and handle them as you want
You can set different targets to the button according to it's state and toggle them in the action methods as shown below.
override func viewDidLoad() {
super.viewDidLoad()
// write your code here
button.addTarget(self, action: #selector(ButtonTappedDuringPrimaryMode(sender:)), for: .touchUpInside)
}
#objc ButtonTappedDuringPrimaryMode(sender: UIButton) {
// write your code here
sender.addTarget(self, action: #selector(ButtonTappedDuringSecondaryMode(sender:)), for: .touchUpInside)
}
#objc ButtonTappedDuringSecondaryMode(sender: UIButton) {
// write your code here
sender.addTarget(self, action: #selector(ButtonTappedDuringPrimaryMode(sender:)), for: .touchUpInside)
}

How to change the color of all Labels in a UIView in Swift?

I found a similar question here. But the problem is it is in OBJ-C. I do not know the code and am working in SWIFT so please can anyone explain and translate this code in swift.
I am still new to swift so please help me.
Regards
Create
var globalColor = UIColor.red
class CustomLbl:UILabel {
override func awakeFromNib() { // inside IB
super.awakeFromNib()
self.textColor = globalColor
}
override func draw(_ rect: CGRect) { // programmatically
super.draw(rect)
self.textColor = globalColor
}
}
And assign it in IB or code , for programmatically call
self.view.setNeedsDisplay()
after you change global color
with an extension. Maybe its not the perfect solution but once you applied it to all needed labels, then it applies to all labels when you make a change. Create a new swift file and put the following code in:
import UIKit
extension UILabel {
func labelColor() {
self.textColor = UIColor.red //or whichever color you want
}
}
And in the viewDidLoad or viewWillLoad you can do:
yourLabel.labelColor()
self.view.subviews.forEach { (view) in // Loop
if let label = view as? UILabel { // check the type
label.textColor = .red // assign the color
}
}
And self is your viewController
As explain in the similar question, you have to
Loop through all the UIView's in self.view.subviews and check if it's
of type UILabel.

How to add something on an image in swift [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have an anatomic picture and on it, I want to print a image like a dot or something when the user taps on the first image (the body) to point out where does it hurts.
I've already read something on UITapGestureRecognizer, but I don't really understood how it works.
Try this:
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap))
self.imageView.addGestureRecognizer(gestureRecognizer)
}
#objc func handleTap(tap: UITapGestureRecognizer) {
let circle = UIView()
circle.center = tap.locationInView(imageView)
circle.frame.size = CGSize(width: 30, height: 30)
circle.layer.backgroundColor = UIColor.redColor().CGColor
circle.layer.cornerRadius = 15
imageView.addSubview(circle)
}

Where to add subviews and constraints for a custom view based on iOS library objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to made a custom view like this :
As you can see, this view relies only on objects from iOS library : UILabel and UISlider.
I want to add as many "element" (name + slider + percentage) as I want. So I was thinking of creating just a "unit" view like this :
and then, adding the number I want programmatically.
So, in order to this, I have to create a new UIView file, but then, where do I add the UILabels, UISlider ? In initWithFrame method ? Are the constraints also to put in this method ? or maybe in "viewDidLoad" method ?
Thanks for your guidance
Just create a custom init.
For example:
-(instancetype)initWithLabelText:(NSString*)text andSliderValue:(NSInteger)sliderValue {...}
in the custom view class you have global properties for the slider and the labels. which gets initialized with the passed values. the method to change the slider value and the label you add to that class as well
Create a new class and make it inherit from UIView.
Then create public properties for all the UI elements you want to control. Alternatively, make the UI elements private and have public counterparts for their value.
Override layoutSubviews() to add UI elements as subviews (make sure you don't add them multiple times by checking for nil) and update their frames.
Alternatively, add them in your init function and add auto-layout constraints if you don't want to deal with frames.
Here's a good starting point:
class CustomView: UIView {
// MARK: -------------------------
// MARK: Properties
var nameLabel: UILabel!
var slider: UISlider!
var percentLabel: UILabel!
// MARK: -------------------------
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Anything that needs to be initialized when loaded from xib or storyboard
}
override init(frame: CGRect) {
super.init(frame: frame)
// Anything that needs to be initialized when loaded programatically
}
// MARK: -------------------------
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
if nil == nameLabel {
nameLabel = UILabel(frame: CGRectZero)
// Set other attributes here
addSubview(nameLabel)
}
// Update the name label frame here
if nil == slider {
slider = UISlider(frame: CGRectZero)
// Set other attributes here
addSubview(slider)
}
// Update the slider frame here
if nil == percentLabel {
percentLabel = UILabel(frame: CGRectZero)
// Set other attributes here
addSubview(percentLabel)
}
// Update the percent label frame here
}
}

iOS ViewController Life Cycle Best Practices [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Does anyone know of a good tutorial that explains in depth the view controller life cycle. I have read the docs so please do not link me to them. I am just looking for a practical explanation of each function such as viewDidLoad and viewWillAppear, viewWillLayoutSubviews, etc, and when best to use them with examples in Swift. If there are no tutorials would anyone be willing to explain them here in their answer.
I show the code for you with using swift.
import UIKit
class LifeCycleViewController: UIViewController {
// MARK: -property
lazy var testBtn: UIButton! = {
var btn: UIButton = UIButton()
btn.backgroundColor = UIColor.redColor()
return btn
}()
// MARK: -life cycle
override func viewDidLoad() {
super.viewDidLoad()
println("View has loaded")
// set the superView backgroudColor
self.view.backgroundColor = UIColor.blueColor()
// add testBtn to the superView
self.view.addSubview(self.testBtn)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("View will appear")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("View has appeared")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
println("View will disappear")
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
println("View has desappeared")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
println("SubViews will layout")
// layout subViews
self.testBtn.frame = CGRectMake(100, 100, 100, 100)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
println("SubViews has layouted")
var testBtn_Width = self.testBtn.frame.width
println("testBtn's width is \(testBtn_Width)")
}
}
Here is the result:
View has loaded
View will appear
SubViews will layout
SubViews has layouted
testBtn's width is 100.0
SubViews will layout
SubViews has layouted
testBtn's width is 100.0
View has appeared
You can see the ViewController's life cycle clearly.
Not bad example on this image.
This is the way I see it.
ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work.
ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.
ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.
ViewWill/DidDisappear - Same idea as WillAppear.
ViewDidUnload/ViewDidDispose - In Objective C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.

Resources