I am using a TTTAttributedLabel in my project. I have managed to change the default color and underlining for any link that I create by modifying the link attributes.
NSArray *pKeys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,
(id)kCTUnderlineStyleAttributeName
, nil];
NSArray *pObjects = [[NSArray alloc] initWithObjects:pAlertColor,[NSNumber numberWithInt:
kCTUnderlineStyleNone], nil];
NSDictionary *pLinkAttributes = [[NSDictionary alloc] initWithObjects:pObjects
forKeys:pKeys];
self.alertMessage.linkAttributes = pLinkAttributes;
self.alertMessage.activeLinkAttributes = pLinkAttributes;
However, I have noticed that when I tap on the link, it turns red momentarily as any other link does when tapped. I need to change this color. Any clues to how that might be done?
Swift 2 Solution:
Specifically, need to set activeLinkAttributes, see below example:
private func subscriptionNoticeWithDelegate(delegate:TTTAttributedLabelDelegate) -> TTTAttributedLabel {
let subscriptionNotice:String = "To turn on all notifications, subscribe to our monthly " +
"service ($0.99/month). If you have already subscribed, please restore your purchase."
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.2
let subscriptionNoticeAttributedString = NSAttributedString(string:subscriptionNotice, attributes: [
NSFontAttributeName: UIFont(name:"HelveticaNeue-Light", size:15)!,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: UIColor.grayColor().CGColor,
])
let subscriptionNoticeLinkAttributes = [
NSForegroundColorAttributeName: UIColor.grayColor(),
NSUnderlineStyleAttributeName: NSNumber(bool:true),
]
let subscriptionNoticeActiveLinkAttributes = [
NSForegroundColorAttributeName: UIColor.grayColor().colorWithAlphaComponent(0.80),
NSUnderlineStyleAttributeName: NSNumber(bool:true),
]
let subscriptionNoticeLabel:TTTAttributedLabel = TTTAttributedLabel(frame:CGRectZero)
subscriptionNoticeLabel.delegate = delegate
subscriptionNoticeLabel.numberOfLines = 0
subscriptionNoticeLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
subscriptionNoticeLabel.textInsets = UIEdgeInsets(top:10, left:15, bottom:0, right:15)
subscriptionNoticeLabel.setText(subscriptionNoticeAttributedString)
subscriptionNoticeLabel.linkAttributes = subscriptionNoticeLinkAttributes
subscriptionNoticeLabel.activeLinkAttributes = subscriptionNoticeActiveLinkAttributes
let subscribeLinkRange = (subscriptionNotice as NSString).rangeOfString("subscribe")
let subscribeURL = NSURL(string:kSubscriptionNoticeSubscribeURL)!
subscriptionNoticeLabel.addLinkToURL(subscribeURL, withRange:subscribeLinkRange)
let restoreLinkRange = (subscriptionNotice as NSString).rangeOfString("restore")
let restoreURL = NSURL(string:kSubscriptionNoticeRestoreURL)!
subscriptionNoticeLabel.addLinkToURL(restoreURL, withRange:restoreLinkRange)
return subscriptionNoticeLabel
}
You will like to look at TTTAttributedLabel documentation, specifically at activeLinkAttributes
activeLinkAttributes
#property (nonatomic, strong) NSDictionary *activeLinkAttributes
Discussion
A dictionary containing the NSAttributedString attributes to be
applied to links when they are in the active state. If nil or an empty
NSDictionary, active links will not be styled. The default active link
style is red and underlined.
Declared In
TTTAttributedLabel.h
You should do something like this
NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary];
[mutableActiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName];
[mutableActiveLinkAttributes setObject:[UIColor greenColor] forKey:(NSString *)kCTForegroundColorAttributeName];
label.activeLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableActiveLinkAttributes];
For Swift 4:
let activeLinkAttributes = NSMutableDictionary(dictionary: attributedLabel.activeLinkAttributes)
activeLinkAttributes[NSAttributedStringKey.foregroundColor] = UIColor.blue
attributedLabel.activeLinkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any]
For Swift 3:
let activeLinkAttributes = NSMutableDictionary(dictionary: attributedLabel.activeLinkAttributes)
activeLinkAttributes[NSForegroundColorAttributeName] = UIColor.blue
attributedLabel.activeLinkAttributes = activeLinkAttributes as NSDictionary as! [AnyHashable: Any]
Full code to set TTTAttributedLabel in Objective-C
#import "TTTAttributedLabel.h"
#property (weak, nonatomic) IBOutlet TTTAttributedLabel *attributedLable;
- (void)viewDidLoad {
[super viewDidLoad];
[self setup];
}
- (void)setup {
_attributedLable.numberOfLines = 0;
NSString *strTC = #"Terms and Condition";
NSString *strPP = #"Privacy Policy";
NSString *string = [NSString stringWithFormat:#"By click continue I agree to %# and %#.",strTC,strPP];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle alloc];
paragraphStyle.lineHeightMultiple = 1.2;
NSAttributedString *fullAttributedString = [[NSAttributedString alloc] initWithString:string attributes:#{
NSFontAttributeName : [UIFont fontWithName:IZFontNameLatoRegular size:15.0],
NSParagraphStyleAttributeName : paragraphStyle
}];
[_attributedLable setTextAlignment:NSTextAlignmentCenter];
[_attributedLable setAttributedText:fullAttributedString];
NSRange rangeTC = [string rangeOfString:strTC];
NSRange rangePP = [string rangeOfString:strPP];
NSDictionary *ppActiveLinkAttributes = #{NSForegroundColorAttributeName : [UIColor blueColor], NSUnderlineStyleAttributeName: #(NSUnderlineStyleNone)};
NSDictionary *ppLinkAttributes = #{NSForegroundColorAttributeName : [UIColor blueColor], NSUnderlineStyleAttributeName: #(NSUnderlineStyleNone)};
_attributedLable.activeLinkAttributes = ppActiveLinkAttributes;
_attributedLable.linkAttributes = ppLinkAttributes;
NSURL *urlTC = [NSURL URLWithString:#"action://TC"];
NSURL *urlPP = [NSURL URLWithString:#"action://PP"];
[_attributedLable addLinkToURL:urlTC withRange:rangeTC];
[_attributedLable addLinkToURL:urlPP withRange:rangePP];
_attributedLable.textColor = [UIColor blackColor];
_attributedLable.delegate = self;
}
//Delegate Method
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if ([url.absoluteString isEqualToString:#"action://TC"]) {
NSLog(#"terms and conditions click");
}
else if ([url.absoluteString isEqualToString:#"action://PP"]){
NSLog(#"privacy policy click");
}
}
Note : Install Pod file : pod 'TTTAttributedLabel'
You can use an attribute "activeLinkAttributes"
NSMutableDictionary* attributes = [NSMutableDictionary dictionaryWithDictionary:self.attributedLabel.activeLinkAttributes];
[attributes setObject:(__bridge id)[UIColor blueColor].CGColor forKey:(NSString*)kCTForegroundColorAttributeName];
self.attributedLabel.activeLinkAttributes = attributes;
For reference, Not changing link color when tapping.
Just disable active link color by code below.
self.tttAttributedLabel.inactiveLinkAttributes = nil;
Related
Is there a way to change the alignment of the message displayed inside a UIAlertController on iOS 8?
I believe accessing the subviews and changing it for the UILabel is not possible anymore.
I have successfully used the following, for both aligning and styling the text of UIAlertControllers:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Left
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody),
NSForegroundColorAttributeName : UIColor.blackColor()
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
You can do a similar thing with the title, if you use "attributedTitle", instead of "attributedMessage"
Swift 3 update
The above still works in Swift 3, but the code has to be slightly altered to this:
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName : UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
NSForegroundColorAttributeName : UIColor.black
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Swift 4 update
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSAttributedStringKey.paragraphStyle: paragraphStyle,
NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
NSAttributedStringKey.foregroundColor: UIColor.black
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Swift 5 update
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
let messageText = NSAttributedString(
string: "message",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.foregroundColor : UIColor.primaryText,
NSAttributedString.Key.font : UIFont(name: "name", size: size)
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Use the below code
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:[title lowercaseString]
message:[message lowercaseString]
preferredStyle:UIAlertControllerStyleAlert];
if (alertStyle == kUIAlertStylePlainText)
{
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
}];
}
if (okTitle) {
UIAlertAction* ok = [UIAlertAction actionWithTitle:[okTitle lowercaseString] style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
callback(alert, action, nil);
}];
[alert addAction:ok];
}
if (cancelTitle) {
UIAlertAction* cancel = [UIAlertAction actionWithTitle:[cancelTitle lowercaseString] style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
callback(alert, nil, action);
}];
[alert addAction:cancel];
}
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.alignment = NSTextAlignmentLeft;
NSMutableAttributedString *atrStr = [[NSMutableAttributedString alloc] initWithString:[message lowercaseString] attributes:#{NSParagraphStyleAttributeName:paraStyle,NSFontAttributeName:[UIFont systemFontOfSize:13.0]}];
[alert setValue:atrStr forKey:#"attributedMessage"];
[viewInstance presentViewController:alert animated:YES completion:nil];
I took up #Amos's answer and made it into a convenient extension:
public extension UIAlertController {
func setMessageAlignment(_ alignment : NSTextAlignment) {
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = alignment
let messageText = NSMutableAttributedString(
string: self.message ?? "",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray
]
)
self.setValue(messageText, forKey: "attributedMessage")
}
}
Then you can simply set the alignment value: myAlert.setMessageAlignment(.left)
Navigate to subview tree until you get to the UILabels for the title and the message
NSArray *viewArray = [[[[[[[[[[[[alertController view] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews];
UILabel *alertTitle = viewArray[0]
UILabel *alertMessage = viewArray[1];
alertMessage.textAlignment = NSTextAlignmentLeft;
However, you may want to make an category for it
#interface UIAlertController (ShowMeTheLabels)
#property (nonatomic, strong) UILabel *titleLabel, *messageLabel;
#end
#implementation UIAlertController (ShowMeTheLabels)
#dynamic titleLabel;
#dynamic messageLabel;
- (NSArray *)viewArray:(UIView *)root {
NSLog(#"%#", root.subviews);
static NSArray *_subviews = nil;
_subviews = nil;
for (UIView *v in root.subviews) {
if (_subviews) {
break;
}
if ([v isKindOfClass:[UILabel class]]) {
_subviews = root.subviews;
return _subviews;
}
[self viewArray:v];
}
return _subviews;
}
- (UILabel *)titleLabel {
return [self viewArray:self.view][0];
}
- (UILabel *)messageLabel {
return [self viewArray:self.view][1];
}
#end
Then you can align the text like this
yourAlertController.messageLabel.textAlignment = NSTextAlignmentLeft;
Swift 4.2 + multiline string linebreak indentation
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.headIndent = 14
let messageText = NSMutableAttributedString(
string: "... multiline string need linebreak indentation ...",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray
]
)
alert.setValue(messageText, forKey: "attributedMessage")
The following method will set the text alignment, while preserving the default font size.
static void makeAlertControllerLeftAligned( UIAlertController* avc )
{
NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease];
paraStyle.alignment = NSTextAlignmentLeft;
NSMutableAttributedString *atrStr =
[[[NSMutableAttributedString alloc] initWithString:avc.message attributes:#{
NSParagraphStyleAttributeName:paraStyle,
NSFontAttributeName: [UIFont preferredFontForTextStyle: UIFontTextStyleFootnote],
}]
autorelease];
[avc setValue:atrStr forKey:#"attributedMessage"];
}
This property exposes the text fields, so could probably be used to configure them:
textFields
The array of text fields displayed by the alert. (read-only)
Declaration
SWIFT
var textFields: [AnyObject]? { get }
OBJECTIVE-C
#property(nonatomic, readonly) NSArray *textFields
Discussion
Use this
property to access the text fields displayed by the alert. The text
fields are in the order in which you added them to the alert
controller. This order also corresponds to the order in which they are
displayed in the alert.
Note: even though it says the property is readonly, it returns an array of text field object references which can be used to modify the controls.
yourAlertController.messageLabel.textAlignment = NSTextAlignmentLeft;
I have a UITextView with multiple URLs that I activate by setting the dataDetectorTypes property to UIDataDetectorTypeLink. I then use the linkTextAttributes property to set the color of the links. Now when the user taps on one of the links (using a UITapGestureRecognizer), I'd like to change the color of that link only. If I change linkTextAttributes, all the links will change color.
How can I change just the color of the link that was tapped on?
If these urls are fixed.
For example:
I have the following urls:
http://www.123.com
http://www.456.com
http://www.789.com
I would put them to an NSAttributedString
Use NSMutableAttributedString to combine them all
NSMutableAttributedString *urlsAttributedText = [[NSMutableAttributedString alloc]init];
NSAttributedString *url1 = [[NSAttributedString alloc]initWithString:NSLocalizedString(#"http://www.123.com\n", nil) attributes:#{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:15.0f]}];
NSAttributedString *url2 = [[NSAttributedString alloc]initWithString:NSLocalizedString(#"http://www.456.com\n", nil) attributes:#{NSForegroundColorAttributeName : [UIColor greenColor], NSFontAttributeName : [UIFont systemFontOfSize:15.0f]}];
NSAttributedString *url3 = [[NSAttributedString alloc]initWithString:NSLocalizedString(#"http://www.789.com\n", nil) attributes:#{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:15.0f]}];
[urlsAttributedText url1];
[urlsAttributedText appendAttributedString:url2];
[urlsAttributedText appendAttributedString:url3];
self.texView.attributedText = urlsAttributedText;
Cheers!
I think I solved it, using a subclass of UITextView called which has a rangeOfLink property.
First, in my UIViewController viewDidLoad:, I add
self.textView.dataDetectorTypes = UIDataDetectorTypeLink; // change for other link types
self.textView.selectable = YES;
self.textView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector(handleTap:)];
tapGesture.cancelsTouchesInView = YES;
[self.textView addGestureRecognizer: tapGesture];
[self.textView setNeedsDisplay]; // force a redraw so that drawRect is called
Then in handleTap, I do this:
MyTextViewWithLink *aTextView = (IDTextViewWithLink *) recognizer.view;
if (aTextView != self.textView)
return;
if (recognizer.state == UIGestureRecognizerStateEnded)
{
CGPoint location = [recognizer locationInView: aTextView];
// this returns an NSTextCheckingResult if location is inside a link
NSTextCheckingResult *result = [self textCheckingResultAtPoint: location inTextView: aTextView];
if (result)
{
aTextView.rangeOfLink = result.range;
[aTextView setNeedsDisplay]; // this will force the color change
// open url
}
}
Finally I override drawRect in my UITextView subclass:
self.linkTextAttributes = [NSDictionary dictionary];
NSError *error = nil;
NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes: NSTextCheckingTypeLink error: &error]; // change for other link types
if (!error && dataDetector)
{
NSArray* resultString = [dataDetector matchesInString: self.text
options: NSMatchingReportProgress
range: NSMakeRange(0, [self.text length])];
if (resultString.count > 0)
{
NSMutableAttributedString *mas = [self.attributedText mutableCopy];
for (NSTextCheckingResult* result in resultString)
{
if (result.resultType == NSTextCheckingTypeLink)
{
NSRange intersection = NSIntersectionRange(result.range, self.rangeOfLink);
if (intersection.length <= 0) // no match
[mas addAttribute: NSForegroundColorAttributeName
value: [UIColor blueColor]
range: self.rangeOfLink];
else
[mas addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: self.rangeOfLink];
}
}
self.attributedText = mas;
}
}
[super drawRect: rect];
Now if the textView has more than one link, only the selected one will change color.
Is there a way to change the alignment of the message displayed inside a UIAlertController on iOS 8?
I believe accessing the subviews and changing it for the UILabel is not possible anymore.
I have successfully used the following, for both aligning and styling the text of UIAlertControllers:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Left
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleBody),
NSForegroundColorAttributeName : UIColor.blackColor()
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
You can do a similar thing with the title, if you use "attributedTitle", instead of "attributedMessage"
Swift 3 update
The above still works in Swift 3, but the code has to be slightly altered to this:
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName : UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
NSForegroundColorAttributeName : UIColor.black
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Swift 4 update
let messageText = NSMutableAttributedString(
string: "The message you want to display",
attributes: [
NSAttributedStringKey.paragraphStyle: paragraphStyle,
NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.body),
NSAttributedStringKey.foregroundColor: UIColor.black
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Swift 5 update
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = alignment
let messageText = NSAttributedString(
string: "message",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.foregroundColor : UIColor.primaryText,
NSAttributedString.Key.font : UIFont(name: "name", size: size)
]
)
myAlert.setValue(messageText, forKey: "attributedMessage")
Use the below code
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:[title lowercaseString]
message:[message lowercaseString]
preferredStyle:UIAlertControllerStyleAlert];
if (alertStyle == kUIAlertStylePlainText)
{
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
}];
}
if (okTitle) {
UIAlertAction* ok = [UIAlertAction actionWithTitle:[okTitle lowercaseString] style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
callback(alert, action, nil);
}];
[alert addAction:ok];
}
if (cancelTitle) {
UIAlertAction* cancel = [UIAlertAction actionWithTitle:[cancelTitle lowercaseString] style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
callback(alert, nil, action);
}];
[alert addAction:cancel];
}
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.alignment = NSTextAlignmentLeft;
NSMutableAttributedString *atrStr = [[NSMutableAttributedString alloc] initWithString:[message lowercaseString] attributes:#{NSParagraphStyleAttributeName:paraStyle,NSFontAttributeName:[UIFont systemFontOfSize:13.0]}];
[alert setValue:atrStr forKey:#"attributedMessage"];
[viewInstance presentViewController:alert animated:YES completion:nil];
I took up #Amos's answer and made it into a convenient extension:
public extension UIAlertController {
func setMessageAlignment(_ alignment : NSTextAlignment) {
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = alignment
let messageText = NSMutableAttributedString(
string: self.message ?? "",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray
]
)
self.setValue(messageText, forKey: "attributedMessage")
}
}
Then you can simply set the alignment value: myAlert.setMessageAlignment(.left)
Navigate to subview tree until you get to the UILabels for the title and the message
NSArray *viewArray = [[[[[[[[[[[[alertController view] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews] firstObject] subviews];
UILabel *alertTitle = viewArray[0]
UILabel *alertMessage = viewArray[1];
alertMessage.textAlignment = NSTextAlignmentLeft;
However, you may want to make an category for it
#interface UIAlertController (ShowMeTheLabels)
#property (nonatomic, strong) UILabel *titleLabel, *messageLabel;
#end
#implementation UIAlertController (ShowMeTheLabels)
#dynamic titleLabel;
#dynamic messageLabel;
- (NSArray *)viewArray:(UIView *)root {
NSLog(#"%#", root.subviews);
static NSArray *_subviews = nil;
_subviews = nil;
for (UIView *v in root.subviews) {
if (_subviews) {
break;
}
if ([v isKindOfClass:[UILabel class]]) {
_subviews = root.subviews;
return _subviews;
}
[self viewArray:v];
}
return _subviews;
}
- (UILabel *)titleLabel {
return [self viewArray:self.view][0];
}
- (UILabel *)messageLabel {
return [self viewArray:self.view][1];
}
#end
Then you can align the text like this
yourAlertController.messageLabel.textAlignment = NSTextAlignmentLeft;
Swift 4.2 + multiline string linebreak indentation
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.headIndent = 14
let messageText = NSMutableAttributedString(
string: "... multiline string need linebreak indentation ...",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),
NSAttributedString.Key.foregroundColor: UIColor.gray
]
)
alert.setValue(messageText, forKey: "attributedMessage")
The following method will set the text alignment, while preserving the default font size.
static void makeAlertControllerLeftAligned( UIAlertController* avc )
{
NSMutableParagraphStyle *paraStyle = [[[NSMutableParagraphStyle alloc] init] autorelease];
paraStyle.alignment = NSTextAlignmentLeft;
NSMutableAttributedString *atrStr =
[[[NSMutableAttributedString alloc] initWithString:avc.message attributes:#{
NSParagraphStyleAttributeName:paraStyle,
NSFontAttributeName: [UIFont preferredFontForTextStyle: UIFontTextStyleFootnote],
}]
autorelease];
[avc setValue:atrStr forKey:#"attributedMessage"];
}
This property exposes the text fields, so could probably be used to configure them:
textFields
The array of text fields displayed by the alert. (read-only)
Declaration
SWIFT
var textFields: [AnyObject]? { get }
OBJECTIVE-C
#property(nonatomic, readonly) NSArray *textFields
Discussion
Use this
property to access the text fields displayed by the alert. The text
fields are in the order in which you added them to the alert
controller. This order also corresponds to the order in which they are
displayed in the alert.
Note: even though it says the property is readonly, it returns an array of text field object references which can be used to modify the controls.
yourAlertController.messageLabel.textAlignment = NSTextAlignmentLeft;
I have a set of NSString values like this:
self.dataArray = #[#"blue", #"orange", #"green", #"red", #"yellow"];
and would like to be able to do something like (after getting one of the above colors set to self.colorString):
self.view.backgroundColor=[UIColor self.colorString + Color];
but obviously can't do that. What is a possible way?
A nearly universal way:
NSDictionary *colors = #{
#"red": [UIColor redColor],
#"green": [UIColor greenColor],
#"blue": [UIColor blueColor]
};
NSString *name = #"blue";
UIColor *c = colors[name];
A truly universal way:
NSString *selName = [NSString stringWithFormat:#"%#Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];
You can try something like this:
SEL myColor = NSSelectorFromString([NSString stringWithFormat:#"%#Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]
Try to store associate your data with the colors in a dictionary:
UIColor *blue = [UIColor blueColor];
UIColor *red = [UIColor redColor];
NSDictionary *colors = #{#"blue" : blue, #"red" : red};
UITextField *pinga = [[UITextField alloc]init];
pinga.textColor = [colors objectForKey:#"red"];
I'm looking for a way to change color in UIRefreshControl.
The text is shown in an NSAttributedString, so I try to use CoreText.framework:
NSString *s = #"Hello";
NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s];
[a addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSRangeFromString(s)];
refreshControl.attributedTitle = a;
The text is shown correctly, but the color is always the default gray.
Any ideas ?
You should be using NSForegroundColorAttributeName, not kCTForegroundColorAttributeName.
Also, the range being passed should be NSMakeRange(0, [s length]);.
In Swift you can set the color of the attributedTitle as follows:
self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: [NSForegroundColorAttributeName: UIColor(red: 255.0/255.0, green: 182.0/255.0, blue: 8.0/255.0, alpha: 1.0)])
Simple version:
NSAttributedString *title = [[NSAttributedString alloc] initWithString:#"Refresh…"
attributes: #{NSForegroundColorAttributeName:[UIColor redColor]}];
refreshControl.attributedTitle = [[NSAttributedString alloc]initWithAttributedString:title];
The "value" parameter you are passing to the "addAttribute" method is a CGColor, use UIColor instead and it will work! [UIColor redColor].CGColor
NSString *s = #"Hello";
NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s];
[a addAttribute:kCTForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(s)];
refreshControl.attributedTitle = a;
NSString *s = #"Hello";
NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:s];
NSDictionary *refreshAttributes = #{
NSForegroundColorAttributeName: [UIColor blueColor],
};
[a setAttributes:refreshAttributes range:NSMakeRange(0, a.length)];
refreshControl.attributedTitle = a;
I found the answer here: http://ioscreator.com/format-text-in-ios6-attributed-strings/
Swift Version 4 (iOS 11)
let myString = "Pull to refresh"
let myAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.black ]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
refreshControl.attributedTitle = myAttrString
use this method,
(id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
(id)initWithAttributedString:(NSAttributedString *)attrStr;
therefore,
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setObject:[UIColor whiteColor] forKey:NSBackgroundColorAttributeName]; //background color :optional
[attributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName]; //title text color :optionala
NSAttributedString *title = [[NSAttributedString alloc] initWithString:#"Refresh!!" attributes:attributes];
_refreshcontrol.attributedTitle = [[NSAttributedString alloc]initWithAttributedString:title];