ios - UITextView 和 UILabel swift 排成一行

标签 ios swift alignment uilabel uitextview

我有一个 UITextView 和一个 UILabel,它们应该排成一行。 textView 是多行的,其宽度应根据标签对齐。标签是单行的,但宽度也可变。但是label的宽度应该比textView的宽度有更高的优先级。 现在的问题是,看起来 textView 的布局适合并且标签必须处理剩余的空间:

there should be "99" displayed right of the chat bubble

这是另一个示例,但是这次 textView 中的文本足够短以适合标签,以便正确显示标签:

enter image description here

那么我怎样才能强制标签先布局,然后 textView 可以使用剩下的空间(这没问题,因为它是多行的)?

项目的初始化:

let captionTextView: UITextView = {
    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.text = ""
    textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)
    textView.textColor = .white
    textView.backgroundColor = .green
    textView.font = .systemFont(ofSize: 16)
    textView.isScrollEnabled = false
    textView.sizeToFit()
    return textView
}()

///////////////////////////////////
//Comments
var commentsIcon: UIButton = {
    let cb = UIButton()
    cb.setImage(#imageLiteral(resourceName: "chatBubble"), for: .normal)
    return cb
}()
var commentsTextLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "99"
    label.textColor = .white
    label.backgroundColor = .green
    label.font = .systemFont(ofSize: 14)
    label.sizeToFit()
    label.numberOfLines = 1
    return label
}()

添加 subview 后的布局细节:

//horizontal constraints

self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]-5-[v1]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": captionTextView, "v1": commentsIcon]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0(15)]-4-[v1]-5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": commentsIcon, "v1": commentsTextLabel]))

最佳答案

您需要调整标签和 textView 上的 contentCompressionResistancePrioritycontentHuggingPriority

标签应该有比 textView 更高的 contentCompressionResistancePriority

关于ios - UITextView 和 UILabel swift 排成一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42960649/

相关文章:

ios - iTunes 连接意外覆盖

iOS7标签栏变化

ios - 如何使用MDCardCollectionCell? [iOS Material 组件]

css - CSS/HTML5 的大小问题

android - 如何将一个元素对齐到相对布局中另一个元素的中心和上方?

ios - 我想暂停数组中的图像

ios - AVAssetExportSession 结合视频文件和视频之间的卡住帧

php - 使用 Alamofire 从 PHP 服务器检索 JSON 时出现问题

ios - 使用 MVP 模式 iOS 将数据传递给另一个 Controller

Android Spinner Gravity 不工作