gpt4 book ai didi

ios - 在Swift中自动调整多行UILabel的大小

转载 作者:行者123 更新时间:2023-12-01 22:22:34 24 4
gpt4 key购买 nike

我已经尝试了一切以在Swift中自动调整UILabel的大小。当文本为一行时,我可以自动调整大小,但是当文本为两行时,它将不再起作用。 UILabel中的文本更改通常大约每10秒发生一次。我尝试过的代码是:

let direction = UILabel(frame: CGRect(x: 95, y: 10, width: screenWidth - 95, height:100))
direction.numberOfLines = 0
direction.adjustsFontSizeToFitWidth = true
direction.lineBreakMode = .byWordWrapping
direction.textAlignment = .center
direction.minimumScaleFactor = 0.2
direction.font = UIFont.boldSystemFont(ofSize: 40)
view.addSubview(direction)
direction.text = "Ffafdafafdfa fafda dfafaf afa"

func updateDirection(update: String){
direction.text = update
}

原始文本“Ffafdafafdfa fafda dfafaf afa”将自动调整大小,但是在调用updateDirection时,字体大小未从40更改。我还尝试将行数设置为2,并删除.byWordWrapping。如何获得UILabel自动调整大小?

最佳答案

下面的代码将frame sizeadjust the font sizedirection label content保持一致。

let backgroundView = UIView(frame: CGRect(x: 5, y: UINavigationController().navigationBar.frame.height + UIApplication.shared.statusBarFrame.height, width: UIScreen.main.bounds.width - 10, height: UIScreen.main.bounds.width - 100))
let direction = UILabel()

override func viewDidLoad() {
super.viewDidLoad()

direction.backgroundColor = UIColor.green
direction.numberOfLines = 0
direction.textAlignment = .center
direction.font = UIFont.boldSystemFont(ofSize: 40)
direction.adjustsFontForContentSizeCategory = true
direction.adjustsFontSizeToFitWidth = true
direction.text = "This is some multiline label with a background colour" // Set or Initiate random function for your array here.

backgroundView.backgroundColor = UIColor.red
view.addSubview(backgroundView)
backgroundView.addSubview(direction)

Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(random), userInfo: nil, repeats: true)

direction.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint(item: direction,
attribute: .leading,
relatedBy: .equal,
toItem: backgroundView,
attribute: .leadingMargin,
multiplier: 1.0,
constant: 0.0).isActive = true

NSLayoutConstraint(item: direction,
attribute: .trailing,
relatedBy: .equal,
toItem: backgroundView,
attribute: .trailingMargin,
multiplier: 1.0,
constant: 0.0).isActive = true


NSLayoutConstraint(item: direction,
attribute: .top,
relatedBy: .equal,
toItem: backgroundView,
attribute: .topMargin,
multiplier: 1.0,
constant: 0.0).isActive = true

NSLayoutConstraint(item: direction,
attribute: .bottom,
relatedBy: .equal,
toItem: backgroundView,
attribute: .bottomMargin,
multiplier: 1.0,
constant: 0.0).isActive = true


}

func random(sender: Timer) {

//Place your random func code here.
}

输出:

enter image description here

关于ios - 在Swift中自动调整多行UILabel的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44038022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com