我创建了一个自定义信息按钮,我想将其放入常规 UILabel 中。 这个想法是让屏幕显示“点击(此处按钮)获取更多信息”。有没有办法在不创建两个 UILabels 的情况下做到这一点?如果创建 2 个标签是唯一的方法,我怎样才能将所有内容放在一行上?
我尝试在 label.text 中执行 (button) 操作,但这显示了按钮的属性而不是放置按钮。我还尝试了 label.addSubview(button) ,它可以工作,但在错误的位置添加了按钮。
最佳答案
最好的方法是使用带有 NSAttributedString 的 UITextView,其中属性之一是您的链接。
let textView = UITextView()
textView.delegate = self
// These allow the link to be tapped
textView.isEditable = false
textView.isScrollEnabled = false
// Removes padding that UITextView uses, making it look more like a UILabel
textView.textContainer.lineFragmentPadding = 0.0
textView.textContainerInset = .zero
然后是 NSAttributedString
let text = "Tap HERE for more information"
let linkText = "HERE"
// Get range for tappable section
let linkRange = (text as NSString).range(of: linkText)
// Styling
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.black
]
// Actual Link!
let linkTextAttributes: [NSAttributedString.Key: Any] = [
.underlineStyle: NSUnderlineStyle.single.rawValue,
.link: "https://www.example.com" //The link you want to link to
]
let attributedString = NSMutableAttributedString(string: text, attributes: attributes)
attributedString.addAttributes(linkTextAttributes, range: linkRange)
然后使用这些 UITextView 委托(delegate)函数
// Removes a lot of the actions when user selects text
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
// Handle the user tapping the link however you like here
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
viewModel.urlTapped(URL)
return false
}
关于ios - 如何在 swift 中的标签中嵌入自定义按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993199/