2016-12-27 2 views
0

Я пытаюсь изменить размер ярлыка, чтобы соответствовать размеру текста, но ответ опубликован here нуждается в немного больше объяснения.Изменить размер метки

Для меня, у меня есть три метки: валюта, целая сумма, двойное количество:

enter image description here

У меня есть три метки из-за того, что обе валюты и двойное количество имеют другой стиль, чем от целого количество. Если я ошибаюсь, пожалуйста, исправьте меня, поскольку у меня не могло быть только одного ярлыка для всех трех.

Все три имеет автоматическое изменение в top-right

В конце концов я должен удалить статические значения, но когда я применяю код ниже, отметив работы:

viewDidLoad() или viewDidAppear():

integerAmountLabel.sizeToFit() 

integerAmountLabel.text = "1" 
// or integerAmountLabel = "280,000" 

Ожидание: £1.00 или £280,000.00. То, что я получил: £1 .00 или £ 1.00

+0

вы используете 'autoLayout'? – Rikh

+0

@Rikh Да, я. – Sylar

+0

Сначала установите текст в таблицу, а затем вызовите метод sizeToFit на метке. –

ответ

2

Как Аман Гупта уже упоминалось, использование приписывали строки. Вот площадка сниппет, объясняющие, как это сделать:

import UIKit 
import PlaygroundSupport 

var str = "Hello, playground" 

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 300)) 
PlaygroundPage.current.liveView = view 

// set up view hierarchy 
view.backgroundColor = .blue 
let label = UILabel() 
label.translatesAutoresizingMaskIntoConstraints = false 
view.addSubview(label) 
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[label]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label": label])) 
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[label]-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["label": label])) 

// set up atributes 
let currencyAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20), NSForegroundColorAttributeName: UIColor.white] 
let integerAmountAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 30), NSForegroundColorAttributeName: UIColor.white] 
let decimalAmountAttributes = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor(white: 1, alpha: 0.7)] 


// set up formatter 
let formatter = NumberFormatter() 
formatter.numberStyle = NumberFormatter.Style.currency 
formatter.locale = Locale(identifier: "en_GB") 

let amount = 8001.9 
let text = formatter.string(from: NSNumber(value: amount))! 
let nsText = text as NSString 

// calculate ranges 
let currencyRange = NSRange(location: 0, length: 1) 
let decimalPointRange = nsText.range(of: ".") 
var integerAmountLocation = currencyRange.location + currencyRange.length 
var integerAmountLength = decimalPointRange.location - integerAmountLocation 
var integerAmountRange = NSRange(location: integerAmountLocation, length: integerAmountLength) 

// configure attributed string 
var attributedText = NSMutableAttributedString(string: text, attributes: decimalAmountAttributes) 
attributedText.setAttributes(currencyAttributes, range: currencyRange) 
attributedText.setAttributes(integerAmountAttributes, range: integerAmountRange) 

label.attributedText = attributedText 

Result

Вы можете получить всю детскую площадку здесь: https://github.com/AleksanderMaj/AttributedString

+0

Да, сэр. Я соглашусь с этим. Очень полезно. Мне может понадобиться создать несколько констант, так как мне нужно будет повторно использовать, например, «currencyAttributes» в другом месте. – Sylar

+1

Фонд имеет класс NumberFormatter, который упрощает форматирование валют и делает его зависящим от языка. 'NumberFormatter.Style.currency' Я обновлю ответ –

1

Вы можете использовать одну метку, это решит все ваши проблемы, а также вам не придется идти на компромисс с styles.This этикеток может быть достигнута с помощью NSAttributedString. Пример показан ниже с выходом, на который вы можете ссылаться.

let string = NSMutableAttributedString(string: "1000.12") 
    string.addAttribute(NSFontAttributeName,value: UIFont.systemFont(ofSize: 25.0), range: NSRange(location: 0, length: 4)) 
    string.addAttribute(NSFontAttributeName,value: UIFont.systemFont(ofSize: 10.0), range: NSRange(location: 5, length: 2)) 

enter image description here

+0

Как именно установить эту метку? – Sylar

+0

, просто используя свойство attributedText UILabel, вы можете установить его на метку. Например, label.attributedText = строка –

+0

Я не могу получить маленький '.12', потому что я установил размер шрифта на ярлыке – Sylar