총알 포인트로 UI 레이블을 포맷하시겠습니까?
포맷이 가능한가요?text
일순간에UILabel
총탄을 보여주기 위해서요?
그렇다면 어떻게 해야 합니까?
혹시 문자열의 글머리 기호를 유니코드 코드 포인트로 사용할 수도 있습니까?
목적-c
myLabel.text = @"\u2022 This is a list item!";
스위프트 4
myLabel.text = "\u{2022} This is a list item!"
덧셈만" • "
심지어 나도 이런 걸 찾고 있었습니다.textView
. 내가 한 일은, 위에 있는 끈을 내 끈과 함께 붙여서 내 것에 전달하는 것입니다.textView
, 마찬가지로 할 수 있습니다labels
또한.
저는 미래의 뷰어를 위해 이렇게 대답했습니다.
여기 Swift와 함께 좋은 해결책이 있습니다.
let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 600)
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let arrayString = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
]
label.attributedText = add(stringList: arrayString, font: label.font, bullet: "")
self.view.addSubview(label)
글머리 기호 특성 추가
func add(stringList: [String],
font: UIFont,
bullet: String = "\u{2022}",
indentation: CGFloat = 20,
lineSpacing: CGFloat = 2,
paragraphSpacing: CGFloat = 12,
textColor: UIColor = .gray,
bulletColor: UIColor = .red) -> NSAttributedString {
let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]
let paragraphStyle = NSMutableParagraphStyle()
let nonOptions = [NSTextTab.OptionKey: Any]()
paragraphStyle.tabStops = [
NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
paragraphStyle.defaultTabInterval = indentation
//paragraphStyle.firstLineHeadIndent = 0
//paragraphStyle.headIndent = 20
//paragraphStyle.tailIndent = 1
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.paragraphSpacing = paragraphSpacing
paragraphStyle.headIndent = indentation
let bulletList = NSMutableAttributedString()
for string in stringList {
let formattedString = "\(bullet)\t\(string)\n"
let attributedString = NSMutableAttributedString(string: formattedString)
attributedString.addAttributes(
[NSAttributedStringKey.paragraphStyle : paragraphStyle],
range: NSMakeRange(0, attributedString.length))
attributedString.addAttributes(
textAttributes,
range: NSMakeRange(0, attributedString.length))
let string:NSString = NSString(string: formattedString)
let rangeForBullet:NSRange = string.range(of: bullet)
attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
bulletList.append(attributedString)
}
return bulletList
}
결과는 다음과 같습니다.
스위프트 4에서 나는 새로운 라인과 함께 " •"를 사용했습니다.
@IBOutlet weak var bulletLabel: UILabel!
let arrayOfLines = ["Eat egg for protein","You should Eat Ghee","Wheat is with high fiber","Avoid to eat Fish "]
for value in arrayOfLines {
bulletLabel.text = bulletLabel.text! + " • " + value + "\n"
}
출력:
신속하게 3.1
lblItemName.text = "\u{2022} This is a list item!"
예. 다음 글귀를 복사하여 붙여넣습니다.•
스위프트의 컴파일러는 Xcode 내에서 원하는 대로 글을 해석하고 표시할 수 있습니다.
재사용하다
extension String {
static var bullet: String {
return "• "
}
}
print(String.bullet + "Buy apples")
let secondPoint: String = .bullet + "Buy oranges"
print(secondPoint)
산출량
• Buy apples
• Buy oranges
리유저블
extension Array where Element == String {
var bulletList: String {
var po = ""
for (index, item) in self.enumerated() {
if index != 0 {
po += "\n"
}
po += .bullet + item
}
return po
}
}
print(["get apples", "get oranges", "get a bannana"].bulletList)
산출량
• get apples
• get oranges
• get a bannana
글머리 기호에 대한 텍스트 들여쓰기를 정렬하려면 다음 방법을 사용하여 다음과 같이 작성할 수 있습니다.NSAttributedString
적절한 압흔 및 간격 특성:
- (NSAttributedString *)attributedStringForBulletTexts:(NSArray *)stringList
withFont:(UIFont *)font
bulletString:(NSString *)bullet
indentation:(CGFloat)indentation
lineSpacing:(CGFloat)lineSpacing
paragraphSpacing:(CGFloat)paragraphSpacing
textColor:(UIColor *)textColor
bulletColor:(UIColor *)bulletColor {
NSDictionary *textAttributes = @{NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor};
NSDictionary *bulletAttributes = @{NSFontAttributeName: font, NSForegroundColorAttributeName: bulletColor};
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.tabStops = @[[[NSTextTab alloc] initWithTextAlignment: NSTextAlignmentLeft location:indentation options:@{}]];
paragraphStyle.defaultTabInterval = indentation;
paragraphStyle.lineSpacing = lineSpacing;
paragraphStyle.paragraphSpacing = paragraphSpacing;
paragraphStyle.headIndent = indentation;
NSMutableAttributedString *bulletList = [NSMutableAttributedString new];
for (NSString *string in stringList) {
NSString *formattedString = [NSString stringWithFormat:@"%@\t%@\n", bullet, string];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedString];
if (string == stringList.lastObject) {
paragraphStyle = [paragraphStyle mutableCopy];
paragraphStyle.paragraphSpacing = 0;
}
[attributedString addAttributes:@{NSParagraphStyleAttributeName: paragraphStyle} range:NSMakeRange(0, attributedString.length)];
[attributedString addAttributes:textAttributes range:NSMakeRange(0, attributedString.length)];
NSRange rangeForBullet = [formattedString rangeOfString:bullet];
[attributedString addAttributes:bulletAttributes range:rangeForBullet];
[bulletList appendAttributedString:attributedString];
}
return bulletList;
}
그리고 당신은 그 방법을 다음과 같이 사용할 수 있습니다.NSArray
문자와 함께 그리고 당신이 이미 가지고 있다는 것을 제공합니다.UILabel
:
NSArray *stringArray = @[@"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
@"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
@"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
@"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
];
label.attributedText = [self attributedStringForBulletTexts:stringArray
withFont:label.font
bulletString:@"•"
indentation:15
lineSpacing:2
paragraphSpacing:10
textColor:UIColor.blackColor
bulletColor:UIColor.grayColor];
이 링크를 확인하세요. 글머리 기호/기타 기호/이미지(속성 사용)로 텍스트를 포맷하기 위해 사용자 지정 보기를 만들었습니다.목록 항목 기호(Swift 3.0)로서 UILabel의 텍스트 속성) https://github.com/akshaykumarboth/SymbolTextLabel-iOS-Swift
import UIKit
class ViewController: UIViewController {
@IBOutlet var symbolView: SymbolTextLabel!
var testString = "Understanding the concept of sales"
var bulletSymbol = "\u{2022}"
var fontsize: CGFloat= 18
override func viewDidLoad() {
super.viewDidLoad()
//First way // Dynamically creating SymbolTextLabel object
let symbolTextLabel = SymbolTextLabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
symbolTextLabel.setText(text: testString, symbolCode: bulletSymbol) //setting text and symbol of text item
symbolTextLabel.setFontSize(textSize: fontsize) // setting font size
//symbolTextLabel.setSpacing(spacing: 5) // setting space between symbol and text
self.view.addSubview(symbolTextLabel)
//second way // from storyboard or interface builder
symbolView.setText(text: testString, symbolCode: bulletSymbol)
//setting text and symbol of text item
symbolView.setFontSize(textSize: fontsize) // setting font size
//symbolView.setSpacing(spacing: 5) // setting space between symbol and text
}
}
@krunal에서 Swift 5로 리팩터된 솔루션은 다음과 같습니다.NSAttributedString
확장명:
import UIKit
public extension NSAttributedString {
static func makeBulletList(from strings: [String],
bulletCharacter: String = "\u{2022}",
bulletAttributes: [NSAttributedString.Key: Any] = [:],
textAttributes: [NSAttributedString.Key: Any] = [:],
indentation: CGFloat = 20,
lineSpacing: CGFloat = 1,
paragraphSpacing: CGFloat = 10) -> NSAttributedString
{
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.defaultTabInterval = indentation
paragraphStyle.tabStops = [
NSTextTab(textAlignment: .left, location: indentation)
]
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.paragraphSpacing = paragraphSpacing
paragraphStyle.headIndent = indentation
let bulletList = NSMutableAttributedString()
for string in strings {
let bulletItem = "\(bulletCharacter)\t\(string)\n"
var attributes = textAttributes
attributes[.paragraphStyle] = paragraphStyle
let attributedString = NSMutableAttributedString(
string: bulletItem, attributes: attributes
)
if !bulletAttributes.isEmpty {
let bulletRange = (bulletItem as NSString).range(of: bulletCharacter)
attributedString.addAttributes(bulletAttributes, range: bulletRange)
}
bulletList.append(attributedString)
}
if bulletList.string.hasSuffix("\n") {
bulletList.deleteCharacters(
in: NSRange(location: bulletList.length - 1, length: 1)
)
}
return bulletList
}
}
나를 위한 해결책은 uilabel에 확장자를 사용하는 것입니다.
extension UILabel{
func setBulletAttributes(bullet:String , text:String){
var attributes = [NSAttributedString.Key: Any]()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.headIndent = (bullet as NSString).size(withAttributes: attributes).width
attributes[.paragraphStyle] = paragraphStyle
self.attributedText = NSAttributedString(string: text, attributes: attributes)
}
이렇게 부르세요.
var bullet = "* "
self.label.setBulletAttributes(bullet:bullet, text: bullet + "Test *****")
저처럼 총알 포인트가 있는 텍스트 뷰 텍스트를 찾으시는 분이 있다면, 아래가 정답입니다.그런데 정적 텍스트에 대해서만 작동합니다.
• Better experience - Refer a friend and How to Play \n• Tournaments performance improvement\n• UI/UX Improvements\n• Critical bug fixes
위의 텍스트를 텍스트뷰에 배정하였습니다.그것은 저에게 의도된 대로 효과가 있었습니다.
여기 총알 포인트가 있는 경고 보기 컨트롤러를 추가했습니다. 이것이 도움이 되기를 바랍니다.
*** 참고:UIALertViewController 전용입니다.
func showBulletPointsAlert(title:String,subTitles:[String],getCompleted: @escaping((_ selected: Int) -> ())) {
let alertController = UIAlertController(title: "\(title)\n", message: nil, preferredStyle: .alert)
let value = convertToList(subTitles: subTitles, font: .boldSystemFont(ofSize: 14))
alertController.setValue(value, forKey: "attributedMessage")
let okAction = UIAlertAction(title: "Continue", style: .default, handler: { _ in
getCompleted(0)
})
alertController.addAction(okAction)
if let rootViewController = UIApplication.shared.windows.first?.rootViewController {
rootViewController.present(alertController, animated: true, completion: nil)
}
}
func convertToList(subTitles: [String],
font: UIFont,
bullet: String = "\u{2022}",
indentation: CGFloat = 20,
lineSpacing: CGFloat = 2,
paragraphSpacing: CGFloat = 12,
textColor: UIColor = .gray,
bulletColor: UIColor = ThemeManager.shared.mainTextColor) -> NSAttributedString {
let textAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor]
let bulletAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: bulletColor]
let paragraphStyle = NSMutableParagraphStyle()
let nonOptions = [NSTextTab.OptionKey: Any]()
paragraphStyle.tabStops = [
NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
paragraphStyle.defaultTabInterval = indentation
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.paragraphSpacing = paragraphSpacing
paragraphStyle.headIndent = indentation
paragraphStyle.lineBreakMode = .byCharWrapping
let bulletList = NSMutableAttributedString()
for titles in subTitles {
let formattedString = "\(bullet)\t\(titles)\n"
let attributedString = NSMutableAttributedString(string: formattedString)
attributedString.addAttributes(
[NSAttributedString.Key.paragraphStyle : paragraphStyle],
range: NSMakeRange(0, attributedString.length))
attributedString.addAttributes(
textAttributes,
range: NSMakeRange(0, attributedString.length))
let string:NSString = NSString(string: formattedString)
let rangeForBullet:NSRange = string.range(of: bullet)
attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
bulletList.append(attributedString)
}
return bulletList
}
언급URL : https://stackoverflow.com/questions/5533851/format-uilabel-with-bullet-points
'sourcecode' 카테고리의 다른 글
Larvel 마이그레이션을 통해 열의 기본값 변경 (0) | 2023.10.01 |
---|---|
행을 열로 동적으로 변환하는 Mysql 쿼리 (0) | 2023.10.01 |
C# WebBrowser 컨트롤 -- AJAX 이후에 문서 요소를 가져오시겠습니까? (0) | 2023.10.01 |
VS 2010에서 C# 앱의 릴리스 빌드를 "디버깅"할 수 있습니까? (0) | 2023.10.01 |
ng include를 사용할 경우 추가 DOM 노드 사용을 방지합니다. (0) | 2023.10.01 |