Swift - 두 줄의 텍스트가 있는 UI 버튼
두 줄의 텍스트로 UIButton을 만들 수 있는지 궁금합니다.저는 각 줄의 글꼴 크기가 달라야 합니다.첫 번째 줄은 17점, 두 번째 줄은 11점입니다.UIButton 안에 두 개의 라벨을 넣는 것을 시도해 보았지만, 버튼의 경계 안에 두도록 할 수 없습니다.
저는 이 모든 것을 프로그래밍 방식이 아닌 UI 빌더에서 하려고 합니다.
감사해요.
두 가지 질문이 있습니다.
두 줄의 텍스트로 UIButton을 만들 수 있는지 궁금합니다.
이것은 스토리보드를 사용하거나 프로그래밍 방식으로 가능합니다.
스토리보드:
줄 바꿈 모드'를 문자 줄 바꿈 또는 워드 줄 바꿈으로 변경하고 Alt/Option + Enter 키를 사용하여 UIButton의 Title 필드에 새 줄을 입력합니다.
프로그래밍 방식:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping;
}
각 라인의 글꼴 크기가 달라야 합니다. 1
최악의 경우에는 사용자 정의를 사용할 수 있습니다.UIButton
클래스를 지정하고 그 안에 두 개의 레이블을 추가합니다.
더 좋은 방법은, 사용하는 것입니다.NSMutableAttributedString
이 작업은 프로그래밍 방식으로만 수행할 수 있습니다.
스위프트 5:
@IBOutlet weak var btnTwoLine: UIButton?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//applying the line break mode
textResponseButton?.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;
let buttonText: NSString = "hello\nthere"
//getting the range to separate the button title strings
let newlineRange: NSRange = buttonText.range(of: "\n")
//getting both substrings
var substring1 = ""
var substring2 = ""
if(newlineRange.location != NSNotFound) {
substring1 = buttonText.substring(to: newlineRange.location)
substring2 = buttonText.substring(from: newlineRange.location)
}
//assigning diffrent fonts to both substrings
let font1: UIFont = UIFont(name: "Arial", size: 17.0)!
let attributes1 = [NSMutableAttributedString.Key.font: font1]
let attrString1 = NSMutableAttributedString(string: substring1, attributes: attributes1)
let font2: UIFont = UIFont(name: "Arial", size: 11.0)!
let attributes2 = [NSMutableAttributedString.Key.font: font2]
let attrString2 = NSMutableAttributedString(string: substring2, attributes: attributes2)
//appending both attributed strings
attrString1.append(attrString2)
//assigning the resultant attributed strings to the button
textResponseButton?.setAttributedTitle(attrString1, for: [])
}
올드 스위프트
@IBOutlet weak var btnTwoLine: UIButton?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//applying the line break mode
btnTwoLine?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping;
var buttonText: NSString = "hello\nthere"
//getting the range to separate the button title strings
var newlineRange: NSRange = buttonText.rangeOfString("\n")
//getting both substrings
var substring1: NSString = ""
var substring2: NSString = ""
if(newlineRange.location != NSNotFound) {
substring1 = buttonText.substringToIndex(newlineRange.location)
substring2 = buttonText.substringFromIndex(newlineRange.location)
}
//assigning diffrent fonts to both substrings
let font:UIFont? = UIFont(name: "Arial", size: 17.0)
let attrString = NSMutableAttributedString(
string: substring1 as String,
attributes: NSDictionary(
object: font!,
forKey: NSFontAttributeName) as [NSObject : AnyObject])
let font1:UIFont? = UIFont(name: "Arial", size: 11.0)
let attrString1 = NSMutableAttributedString(
string: substring2 as String,
attributes: NSDictionary(
object: font1!,
forKey: NSFontAttributeName) as [NSObject : AnyObject])
//appending both attributed strings
attrString.appendAttributedString(attrString1)
//assigning the resultant attributed strings to the button
btnTwoLine?.setAttributedTitle(attrString, forState: UIControlState.Normal)
}
산출량
저는 두 개의 다른 글꼴 크기가 필요하지 않다는 것을 제외하고는 거의 같은 주제를 찾고 있었습니다.간단한 해결책을 찾는 경우:
let button = UIButton()
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.setTitle("Foo\nBar", for: .normal)
button.titleLabel?.textAlignment = .center
button.sizeToFit()
button.addTarget(self, action: #selector(rightBarButtonTapped), for: .allEvents)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
대부분의 솔루션에서 줄 바꿈 모드를 "문자 줄 바꿈"으로 설정하는 동안 두 번째 줄이 첫 번째 줄과 정렬된 상태로 유지된다는 문제를 발견했습니다.
모든 선의 중심을 맞춥니다.제목을 일반에서 속성으로 변경하면 각 행을 가운데로 지정할 수 있습니다.
줄 바꿈을 문자 줄 바꿈으로 변경합니다. 버튼을 선택하고 속성 검사기에서 줄 바꿈으로 이동하여 문자 줄 바꿈으로 변경합니다.
SWIFT 3 구문
let str = NSMutableAttributedString(string: "First line\nSecond Line")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 17), range: NSMakeRange(0, 10))
str.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(11, 11))
button.setAttributedTitle(str, for: .normal)
저는 이것을 고쳤고 저의 해결책은 스토리보드에만 있었습니다.
변경 사항:
Identity Inspector -> User Defined Runtime Attributes(이러한 KeyPath)에 다음과 같이 추가되었습니다.
- 선의 수 = 2
- titleLabel.textAlignment = 1
속성 검사기에 추가했습니다.
- 줄 바꿈 = 단어 랩
이 중 일부는 코드로 작성해야 합니다.IB에서 두 개의 다른 글꼴을 설정할 수 없습니다.줄 바꿈 모드를 캐릭터 랩으로 바꾸는 것 외에도 제목을 정하기 위해서는 이런 것이 필요하지만,
override func viewDidLoad() {
super.viewDidLoad()
var str = NSMutableAttributedString(string: "First line\nSecond Line")
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(17), range: NSMakeRange(0, 10))
str.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: NSMakeRange(11, 11))
button.setAttributedTitle(str, forState: .Normal)
}
Xcode 13(iOS 15)이 포함된 새로운 기능
Xcode 13부터는 버튼의 제목과 부제가 별도로 설정될 수 있습니다.
스토리보드 사용:
[속성 관리자] 단추에서 제목별 "속성"을 선택합니다.그런 다음 제목과 부제의 글꼴 크기를 변경합니다.
또는 프로그래밍 방식:
// Create Title
let titleSettings = AttributeContainer.font( UIFont(name: "HelveticaNeue-Italic", size: 17)! )
yourButton.configuration?.attributedTitle = AttributedString("Button's Title", attributes: titleSettings)
// Create Subtitle
let subtitleSettings = AttributeContainer.font( UIFont(name: "HelveticaNeue-Italic", size: 11)! )
yourButton.configuration?.attributedSubtitle = AttributedString("Button's Subtitle", attributes: subtitleSettings)
한 가지 방법은 레이블을 사용하는 것입니다.제가 이렇게 했는데, 잘 되는 것 같아요.이것을 UIButton으로 만든 다음 레이블을 노출시킬 수 있습니다.이게 말이 되는지 모르겠네요.
let firstLabel = UILabel()
firstLabel.backgroundColor = UIColor.lightGrayColor()
firstLabel.text = "Hi"
firstLabel.textColor = UIColor.blueColor()
firstLabel.textAlignment = NSTextAlignment.Center
firstLabel.frame = CGRectMake(0, testButton.frame.height * 0.25, testButton.frame.width, testButton.frame.height * 0.2)
testButton.addSubview(firstLabel)
let secondLabel = UILabel()
secondLabel.backgroundColor = UIColor.lightGrayColor()
secondLabel.textColor = UIColor.blueColor()
secondLabel.font = UIFont(name: "Arial", size: 12)
secondLabel.text = "There"
secondLabel.textAlignment = NSTextAlignment.Center
secondLabel.frame = CGRectMake(0, testButton.frame.height * 0.5, testButton.frame.width, testButton.frame.height * 0.2)
testButton.addSubview(secondLabel)
안타깝게도 CollectionView 내에 여러 줄로 된 버튼을 사용하고자 할 때 제안된 솔루션이 제대로 작동하지 않았습니다.그런 다음 동료가 저에게 같은 문제가 발생할 경우 공유하고 싶은 해결 방법을 보여주었습니다. 이것이 도움이 되기를 바랍니다!UIControl에서 상속되는 클래스를 만들고 레이블을 사용하여 확장합니다. 레이블은 단추와 유사하게 작동합니다.
class MultilineButton: UIControl {
let label: UILabel = {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.numberOfLines = 0
$0.textAlignment = .center
return $0
}(UILabel())
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(label)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
label.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor),
label.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),
label.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor)
])
}
override var isHighlighted: Bool {
didSet {
backgroundColor = backgroundColor?.withAlphaComponent(isHighlighted ? 0.7 : 1.0)
label.textColor = label.textColor.withAlphaComponent(isHighlighted ? 0.7 : 1.0)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
내 방식:
func setButtonTitle(title: String, subtitle: String, button: UIButton){
//applying the line break mode
button.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping;
let title = NSMutableAttributedString(string: title, attributes: Attributes.biggestLabel)
let subtitle = NSMutableAttributedString(string: subtitle, attributes: Attributes.label)
let char = NSMutableAttributedString(string: "\n", attributes: Attributes.biggestLabel)
title.append(char)
title.append(subtitle)
button.setAttributedTitle(title, for: .normal)
}
언급URL : https://stackoverflow.com/questions/30679370/swift-uibutton-with-two-lines-of-text
'programing' 카테고리의 다른 글
mariadb에 제대로 연결할 수 없습니다. (0) | 2023.09.04 |
---|---|
javascript/jquery를 사용하여 excel로 내보낸 후 HTML 테이블 스타일 유지 (0) | 2023.09.04 |
python의 __init_ 상속 및 재정의 (0) | 2023.09.04 |
쿼리에서 연속 제한 및 오프셋이 잘못 배치되었습니다. (0) | 2023.09.04 |
모달의 부트스트랩 3 및 유튜브 (0) | 2023.09.04 |