How to shorten tab bar config codes? - swift

I have a configuration code for UITabBarItem but it is too much. Is there any way to shorten this code? I couldn't find any extension for that.
let selectedColor = #colorLiteral(red: 0.3921568627, green: 0.168627451, blue: 0.4509803922, alpha: 1)
let deselectedColor = #colorLiteral(red: 0.5843137255, green: 0.6470588235, blue: 0.6509803922, alpha: 1)
let selectedFont = UIFont(name: "SFProDisplay-Bold", size: 10)!
let deselectedFont = UIFont(name: "SFProDisplay-Regular", size: 10)!
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: deselectedFont, NSAttributedString.Key.foregroundColor : deselectedColor], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: selectedFont, NSAttributedString.Key.foregroundColor : selectedColor], for: .selected)
If there are any extensions for UITabBar and UITabBarItems, can you please share them with me?

One thing you can do is to get rid of all NSAttributedString.Keys, because swift can infer that itself.
UITabBarItem.appearance().setTitleTextAttributes([.font: deselectedFont, .foregroundColor : deselectedColor], for: .normal)

Related

The tag system for the question isn't working as the exchange change only occurs on the last button

Button Method
#objc func buttonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for i in 0..<buttonNames.count{
index+=i
button = Button()
button.setTitle(buttonNames[i], for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
button.tag = index
button.addTarget(self, action: selectors[i], for: .touchUpInside)
button.addTarget(self, action: selectorsColor[i], for: .touchDown)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
Button handler methods
#objc func colorButton1(){
if button.tag == 0 {
button.backgroundColor = #colorLiteral(red: 0.1123025946, green: 1, blue: 0.03079073749, alpha: 1)
}
else {
button.backgroundColor = #colorLiteral(red: 0.7974829231, green: 0.09321228972, blue: 0.09321228972, alpha: 1)
}
}
#objc func colorButton2(){
if button.tag == 1 {
button.backgroundColor = #colorLiteral(red: 0.07117979832, green: 0.8973241221, blue: 0, alpha: 1)
}
else {
button.backgroundColor = #colorLiteral(red: 0.7312681945, green: 0.1133923198, blue: 0.06002510149, alpha: 1)
}
}
#objc func colorButton3(){
if button.tag == 2 {
button.backgroundColor = #colorLiteral(red: 0.1123025946, green: 1, blue: 0.03079073749, alpha: 1)
}
else {
button.backgroundColor = #colorLiteral(red: 0.6805654408, green: 0.1003367522, blue: 0.09689761347, alpha: 1)
}
}
#objc func colorButton4(){
if button.tag == 3 {
button.backgroundColor = #colorLiteral(red: 0.1123025946, green: 1, blue: 0.03079073749, alpha: 1)
}
else {
button.backgroundColor = #colorLiteral(red: 0.7620294414, green: 0.05229266211, blue: 0.09308676813, alpha: 1)
}
}
Every time I press the button it keeps changing colour to the last button, even after tagging each button, the colour change only occurs in the last button and not sure how to change the code to allow the colour change to happen on other button when pressed.
Thank you in advance.
As I said in the comments, the buttons array contains 4 items which all point – due to reference semantics – to the same instance, the lastly added Button instance. So does also the button property.
You need something like this, it creates four different Button instances and uses one action method, I don't know what the second selector does so I commented it out.
The logic: The sender parameter is the just tapped button, first set all background colors except the current button to their appropriate red colors, then set the background color of the current button to the green color. The references to the buttons are taken from the buttons array.
for i in 0..<buttonNames.count{
let button = Button()
button.setTitle(buttonNames[i], for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
button.tag = i
button.addTarget(self, action: #selector(colorButton), for: .touchUpInside)
// button.addTarget(self, action: selectorsColor[i], for: .touchDown)
}
#objc func colorButton(_ sender : Button) {
let offColors = [#colorLiteral(red: 0.7974829231, green: 0.09321228972, blue: 0.09321228972, alpha: 1),
#colorLiteral(red: 0.7312681945, green: 0.1133923198, blue: 0.06002510149, alpha: 1),
#colorLiteral(red: 0.6805654408, green: 0.1003367522, blue: 0.09689761347, alpha: 1),
#colorLiteral(red: 0.7620294414, green: 0.05229266211, blue: 0.09308676813, alpha: 1)]
for i in 0..<4 where i != sender.tag {
buttons[i].backgroundColor = offColors[i]
}
switch sender.tag {
case 0: sender.backgroundColor = #colorLiteral(red: 0.1123025946, green: 1, blue: 0.03079073749, alpha: 1)
case 1: sender.backgroundColor = #colorLiteral(red: 0.07117979832, green: 0.8973241221, blue: 0, alpha: 1)
case 2: sender.backgroundColor = #colorLiteral(red: 0.1123025946, green: 1, blue: 0.03079073749, alpha: 1)
case 3: sender.backgroundColor = #colorLiteral(red: 0.1123025946, green: 1, blue: 0.03079073749, alpha: 1)
default: break
}
}

Swift How to process multiple button UI elegantly?

In my viewController I need to process button UI
I think my approach to process UI is not efficient
What if someday I need to do more button?
Today I just happen to have only three.....
Just want user press one of three, and others keep original color
like make user feel which one they press in many button
Here's my #IBAction
#IBAction func btnPress (_ sender: UIButton) {
let clickedBackgroundColor = UIColor(red: 1, green: 153, blue: 202, a: 1)
let clickedTextColor = UIColor(red: 255, green: 255, blue: 255, a: 1)
let originBackgroundColor = UIColor(red: 216, green: 247, blue: 250, a: 1)
let originTextColor = UIColor(red: 0, green: 71, blue: 88, a: 1)
switch sender {
case btnA:
btnA.backgroundColor = clickedBackgroundColor
btnA.setTitleColor(clickedTextColor, for: .normal)
btnA.underline()
btnB.backgroundColor = originBackgroundColor
btnB.setTitleColor(originTextColor, for: .normal)
btnC.backgroundColor = originBackgroundColor
btnC.setTitleColor(originTextColor, for: .normal)
case btnB:
btnB.backgroundColor = clickedBackgroundColor
btnB.setTitleColor(clickedTextColor, for: .normal)
btnB.underline()
btnA.backgroundColor = originBackgroundColor
btnA.setTitleColor(originTextColor, for: .normal)
btnC.backgroundColor = originBackgroundColor
btnC.setTitleColor(originTextColor, for: .normal)
case btnC:
btnC.backgroundColor = clickedBackgroundColor
btnC.setTitleColor(clickedTextColor, for: .normal)
btnC.underline()
btnA.backgroundColor = originBackgroundColor
btnA.setTitleColor(originTextColor, for: .normal)
btnB.backgroundColor = originBackgroundColor
btnB.setTitleColor(originTextColor, for: .normal)
default:break
}
}
And My UIButton Extension for adding underline
I can only add underline but how to remove it if user click other button?
extension UIButton {
func underline() {
guard let text = self.titleLabel?.text else { return }
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: text.count))
self.setAttributedTitle(attributedString, for: .normal)
}
}
I'm really new, not good at questioning if need more info just ask for me, Thanks.
You simply can create an Outlet Collection for all buttons instead of explicitly creating an array of buttons and use that to set the button's properties as per the selection, i.e.
#IBOutlet var buttons: [UIButton]!
Usage:
#IBAction func btnPress (_ sender: UIButton) {
let clickedBackgroundColor = UIColor(red: 1, green: 153, blue: 202, a: 1)
let clickedTextColor = UIColor(red: 255, green: 255, blue: 255, a: 1)
let originBackgroundColor = UIColor(red: 216, green: 247, blue: 250, a: 1)
let originTextColor = UIColor(red: 0, green: 71, blue: 88, a: 1)
buttons.forEach { (button) in
button.backgroundColor = (button == sender) ? clickedBackgroundColor : originBackgroundColor
button.setTitleColor((button == sender) ? clickedTextColor : originTextColor, for: .normal)
if button == sender {
button.underline()
}
}
}
Note: Also, there is no need to traverse the array twice. One single traversal will work fine.

Trouble Referencing UIButton using NSMutableAttributedString in Instantiated View Controller

As soon as my view controller loads, I am presented with a button (gray background with white font) that displays the text “Sto 1”. This is called in viewWillLayoutSubviews and the title is set using a NSMutableAttributedString. “Sto” is short for store.
For my application, I would like the user to be able to select the Sto 1 button and be able to store a number that is presented on a UILabel. I am able to grab the current number being displayed but I’m unable to update the text inside my Sto 1 button using NSMutableAttributedString. In other words I want to go from the button showing “Sto 1” to displaying some number (e.g., 12).
Thank you all for any help you may be able to provide me. I am still relatively new to Swift and I have been trying to resolve this issue over the past week.
import UIKit
class ViewController: UIViewController {
var fontConstant = CGFloat()
var someRandomNumberDisplayedOnAUILabel = String(12)
#IBOutlet weak var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillLayoutSubviews() {
fontConstant = 1
let myString = "Sto 1"
let myAttributes = [NSAttributedString.Key.foregroundColor : UIColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0), NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10 * fontConstant)]
let mutableAttributedString = NSMutableAttributedString(string: myString, attributes: myAttributes)
myButton.setAttributedTitle(mutableAttributedString, for: .normal)
myButton.backgroundColor = UIColor(red: 94/255.0, green: 94/255.0, blue: 94/255.0, alpha: 1.0)
}
#IBAction func myButtonAction(_ sender: Any) {
let myAttributes = [NSAttributedString.Key.foregroundColor : UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10 * fontConstant)]
let mutableAttributedString = NSMutableAttributedString(string: someRandomNumberDisplayedOnAUILabel, attributes: myAttributes)
myButton.setAttributedTitle(mutableAttributedString, for: .normal)
myButton.backgroundColor = UIColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0)
}}
Normally, you would use setTitle(:for:) to change the text on a UIButton. But since you're working with an NSMutableAttributedString you will need the setAttributedTitle(:for:) function. I think this might be what you're looking for:
myButton.setAttributedTitle(myNSMutableAttributedString, for: .normal)
Heads up, though. You might need to call this function for the different control states and not just .normal otherwise you might see different text for an instant as the button is highlighted. Here is a list of the control states.
EDIT:I would try referencing the sender in the IBAction instead of myButton. This might be a quick fix:
#IBAction func myButtonAction(_ sender: Any) {
let myAttributes = [NSAttributedString.Key.foregroundColor : UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10 * fontConstant)]
let mutableAttributedString = NSMutableAttributedString(string: someRandomNumberDisplayedOnAUILabel, attributes: myAttributes)
guard let button = sender as? UIButton else {
print("Error: sender was not a button")
return
}
button.setAttributedTitle(mutableAttributedString, for: .normal)
button.backgroundColor = UIColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0)
}
EDIT #2:If you're losing the reference to your IBOutlet you might be able to work around that by assigning a selector to the button before you lose it. Try this:
override func viewDidLoad() {
super.viewDidLoad()
// Add the action to the button rather than holding on to the IBOutlet
myButton.addTarget(self, action: #selector(RideInProgressViewController.myAction(sender:)), for: .touchUpInside)
}
#objc private func myAction(sender: Any) {
guard let button = sender as? UIButton else {
print("Error: sender was not a button")
return
}
let myAttributes = [NSAttributedString.Key.foregroundColor : UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0), NSAttributedString.Key.font : UIFont.systemFont(ofSize: 10 * fontConstant)]
let mutableAttributedString = NSMutableAttributedString(string: someRandomNumberDisplayedOnAUILabel, attributes: myAttributes)
button.setAttributedTitle(mutableAttributedString, for: .normal)
button.backgroundColor = UIColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0)
}

UISegmentControl underline not on top in some cases

I'm trying to create a segment control with an underline for the selected segment. I've found a few code snippets to do this but they seem to exhibit the same behavior where the underline is beneath the UISegment of the UISegment Control. In this particular case, I'm using a UITableView custom cell with a UISegmentControl that has constraints to the top, left, bottom and right corners of the cell. Only the 2nd segment shows up properly. Here is what the debug view hierarchy looks like:
Here is the code that I'm using:
extension UISegmentedControl{
func removeBorder(){
let backgroundImage = UIImage.getColoredRectImageWith(color: UIColor.white.cgColor, andSize: self.bounds.size)
self.setBackgroundImage(backgroundImage, for: .normal, barMetrics: .default)
self.setBackgroundImage(backgroundImage, for: .selected, barMetrics: .default)
self.setBackgroundImage(backgroundImage, for: .highlighted, barMetrics: .default)
let deviderImage = UIImage.getColoredRectImageWith(color: UIColor.white.cgColor, andSize: CGSize(width: 1.0, height: self.bounds.size.height))
self.setDividerImage(deviderImage, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
self.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.gray], for: .normal)
self.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(red: 67/255, green: 129/255, blue: 244/255, alpha: 1.0)], for: .selected)
}
func addUnderlineForSelectedSegment(){
removeBorder()
let underlineWidth: CGFloat = self.bounds.size.width / CGFloat(self.numberOfSegments)
let underlineHeight: CGFloat = 2.0
let underlineXPosition = CGFloat(selectedSegmentIndex * Int(underlineWidth))
let underLineYPosition = self.bounds.size.height - 5.0
let underlineFrame = CGRect(x: underlineXPosition, y: underLineYPosition, width: underlineWidth, height: underlineHeight)
let underline = UIView(frame: underlineFrame)
underline.backgroundColor = UIColor(red: 67/255, green: 129/255, blue: 244/255, alpha: 1.0)
underline.tag = 1
self.addSubview(underline)
}
func changeUnderlinePosition(){
guard let underline = self.viewWithTag(1) else {return}
let underlineFinalXPosition = (self.bounds.width / CGFloat(self.numberOfSegments)) * CGFloat(selectedSegmentIndex)
UIView.animate(withDuration: 0.1, animations: {
underline.frame.origin.x = underlineFinalXPosition
})
}
}
Anyone have any ideas what is causing this?
This feels a bit hacky but I changed the following line:
self.addSubview(underline)
To the following:
for each in self.subviews {
each.addSubview(underline)
Now, it works properly. Even in the debug view hierarchy, I only see one underline UIView. Strange.
Still interested in any other answers that might be a better solution.

update/replace text in textview

I have a TextField in the first view controller where the user enter his name. In the second view controller i Have a form in textview where the user entered details to be replaced the specific word in the specific place.
I cannot able to find the right guidance from the various searches, where I can only find to format the text/color, etc. My object is to replace the existing text with user filled data.
import UIKit
class SandyaViewController: UIViewController, UITextFieldDelegate {
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "SViewController" {
if let nextVC = segue.destination as? SPViewController {
nextVC.yourName = self.nameTextField.text!
nextVC.address = self.addressTextField.text!
}
}
}
}
class SPViewController: UIViewController {
var yourName: String!
var address: String!
#IBOutlet weak var formTextView: UITextView!
myTextView.text = "This is to certify , that I yourname residing at home address....."
let attributedString = NSMutableAttributedString(string: "This is to certify , that I your name residing at home address .........\n")
let attributes1: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.foregroundColor: UIColor(red: 153/255, green: 51/255, blue: 255/255, alpha: 1.0),
NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 15)!,
NSAttributedStringKey.backgroundColor: UIColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1.0)
]
attributedString.addAttributes(attributes1, range: NSMakeRange(28, 9))
let attributes3: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.foregroundColor: UIColor(red: 230/255, green: 0/255, blue: 0/255, alpha: 1.0),
NSAttributedStringKey.backgroundColor: UIColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1.0)
]
attributedString.addAttributes(attributes3, range: NSMakeRange(51, 12))
Here I want the replace the attributes1 value with yourName and attributes3 value with address
myTextView.text = "This is to certify , that I attributes1 residing at home attributes3....."
I assume the I have detailed properly
Thanks