I want to show Button title like this
but my output is comming like this even after centralising the title
frmbtn is the outlet of button And the Code I am Using for this is
frmbtn.setTitle("From Station\nSTN\nSTATION NAME", forState: UIControlState.Normal)
frmbtn.titleLabel!.numberOfLines = 3
frmbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
And Can we put different text sizes in the button title ?
Here is whole as you want.
import UIKit
class ViewController: UIViewController {
#IBOutlet var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var str : NSMutableAttributedString = NSMutableAttributedString(string: "From station\nSTN\nStation Name")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSRange(location: 13,length: 3))
button.setAttributedTitle(str, forState: UIControlState.Normal)
button.titleLabel!.lineBreakMode = .ByWordWrapping
button.titleLabel?.textAlignment = .Center
button.titleLabel?.adjustsFontSizeToFitWidth = true
}
}
in Easy way you can also give space like this:
frmbtn.setTitle("From Station\n STN\nSTATION NAME", forState: UIControlState.Normal) \\give here space after \n and see the result
frmbtn.titleLabel!.numberOfLines = 3
frmbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
You have to set the text alignment on the titleLabel itself. Also you can change the font size as part of the font property.
scanButton.titleLabel!.numberOfLines = 3
scanButton.titleLabel!.textAlignment = NSTextAlignment.Center;
scanButton.titleLabel!.font = UIFont.systemFontOfSize(40);
To set a multiline title on a UIButton, check this forum post which describes changing the button label.
myButton.titleLabel.textAlignment = UITextAlignmentCenter;
myButton.titleLabel.lineBreakMode = UILineBreakModeCharacterWrap;
[myButton setTitle:#"From Station STN station name" forState:UIControlStateNormal];
Related
Change the title color of a Default styled button programmatically is straightforward.
We just need to perform
button.setTitleColor(.red, for: .normal)
But, what about a Filled styled button?
Using 1 liner UIButton.setTitleColor has no effect.
After several trial and error, I have came out with an "ugly" way
if let configuration = button.configuration {
let attributedStringColor = [NSAttributedString.Key.foregroundColor : UIColor.red];
let attributedString = NSAttributedString(
string: button.titleLabel?.text ?? "",
attributes: attributedStringColor
)
do {
let a = try AttributedString(attributedString, including: \.uiKit)
var c = configuration
c.attributedTitle = a
button.configuration = c
} catch {
}
}
Even though that works, I just feel it is not the right way, to require so many lines of code to change the button title color.
May I know, what is the right way to change the title color of a Filled styled UIButton programmatically?
You can make a neat little extension to AttributeContainer:
extension AttributeContainer {
init(foregroundColor: UIColor) {
self.init()
self.foregroundColor = foregroundColor
}
}
And then use it to set the button's title and color:
button.configuration = .filled()
button.configuration?.attributedTitle = AttributedString("ButtonTitle", attributes: .init(foregroundColor: .systemRed))
..or you can just do this:
button.configuration?.attributedTitle?.foregroundColor = .systemRed
You can also use the .baseForegroundColor configuration property:
var cfg = tintedBtn.configuration
cfg?.baseForegroundColor = .red
tintedBtn.configuration = cfg
I'm a beginner at swift and I've found that this StackOverflow question and this StackOverflow question has not helped me with my case, most probably because I've coded it differently to them (ie Swift, not Obc).
private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setTitle("dont have an account? sign up!", for: .normal) //line 4
return button
I would like the text "sign up!" in line 4 to be formatted in bold but haven't found anything online that can support it with the current way I've coded it.
Use button setAttributedTitle property for set attributed text.
First, create attributed text.
Here, I created a string extension for bold attributed text. Which return attributed text and set this attributed text to button.
extension String {
/// Return attributed string
/// - Parameter text: String text for bold text.
func getAttributedBoldText(text: String) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self, attributes: [.foregroundColor: UIColor.blue])
if let range = self.range(of: text) {
let startIndex = self.distance(from: self.startIndex, to: range.lowerBound)
let range = NSMakeRange(startIndex, text.count)
attributedString.addAttributes([.font : UIFont.boldSystemFont(ofSize: 20)], range: range)
}
return attributedString
}
}
Usage :
private let createAccountButton: UIButton = {
let button = UIButton()
button.setTitleColor(.white, for: .normal)
button.setAttributedTitle("dont have an account? sign up!".getAttributedBoldText(text: "sign up!"), for: .normal) // Here
return button
}()
Note: Modify the extension attributed function as per your layout.
I have taken outlet collection of labels and these labels will have same fonts and I want to set the font for all labels in one line.
It will go like this:
labels.forEach { $0.font = UIFont.systemFont(ofSize: 43) }
Here is how,
class ViewController: UIViewController {
#IBOutlet var labels: [UILabel]!
override func viewDidLoad() {
super.viewDidLoad()
labels.forEach { (label) in
label.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
//give the font as per your requirement...
}
}
}
Just get all the labels you want inside an array of Labels
let myLabels: [UILabel] = [label1,label2,label3]
then make a Loop to set the font of each one of the labels..
for text in myLabels {
text.font = UIFont(name: "Kefa-Regular", size: 10)
//The 'name' is the name of the font you want, it's also could be a custom one.
}
if it's an Outlet Collection you can skip the Array part of the code.
I have a button that I create in interface builder that highlights the entire button on tap. I do nothing in code, simply ctrl+drag to my view controller file.
Then I have another button that I create programatically with this code.
let goToButton = UIButton()
goToButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
goToButton.titleLabel?.font = UIFont(name: "Arial", size: 18)
goToButton.setTitle("◀︎ Go To Form", forState: .Normal)
goToButton.backgroundColor = UIColor.whiteColor()
goToButton.showsTouchWhenHighlighted = true // Should highlight entire button?
but on tap it look like this.
How can I make it so that it matches the highlight like a button from interface builder
set your button type as Custom or `System and try once , change this
let goToButton = UIButton()
into
let goToButton = UIButton(type:.System)
or
let goToButton = UIButton(type:.Custom)
and hide this
goToButton.showsTouchWhenHighlighted = true
I want to customize the cancel button inside the UISearchBar, that appears when the user type a text, to clear the text, see the image, I want to change the tint color of the button inside the red square NOT the button with "cancel" text
What I have tried :
[[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor redColor]];
but it changes the color of the button with the text "cancel" not the icon to clear the text inside the textfield
it's not a duplicate question because I want to change the tint of the default clear image, NOT using a custom image, something like that :
How to change the tint color of the clear button on a UITextField
but for UISearchBar
UIImage *imgClear = [UIImage imageNamed:#"clear"];
[mySearchBar setImage:imgClear forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
Swift 4.2, 4.1+
It seems that the currentImage is nil for clearButton from Swift 4.1+. It might be working in the older versions.
So i created this class and the addition here is to provide your own image and color for clear button.
class SearchBar: UISearchBar {
var clearButtonImage: UIImage?
var clearButtonColor: UIColor = .white
override func layoutSubviews() {
super.layoutSubviews()
if let textField = self.value(forKey: "searchField") as? UITextField {
if let clearButton = textField.value(forKey: "clearButton") as? UIButton {
update(button: clearButton, image: self.clearButtonImage, color: clearButtonColor)
}
}
}
private func update(button: UIButton, image: UIImage?, color: UIColor) {
let image = (image ?? button.currentImage)?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.setImage(image, for: .highlighted)
button.tintColor = color
}
}
So now you can set the clearButton image as below to make it work,
let searchBar = SearchBar()
searchBar.clearButtonImage = UIImage(named: "clearIcon")
searchBar.clearButtonColor = .green
Storyboard or XIB
You have to set the SearchBar class as custom class for search bar shown below,
And outlet as below to set the images and colors etc
#IBOutlet private weak var searchBar: SearchBar!