簡體   English   中英

如何在 Swift 中使 UILabel 成為一個圓圈

[英]How to make UILabel in Swift a circle

我試圖使 Swift 中的 UILabel 成為一個完美的圓圈。 我目前正在使用以下內容:

pResult.layer.masksToBounds = true
pResult.layer.cornerRadius = 125

問題在於它在 6s plus 上工作正常,但任何其他尺寸都不會變成圓形。 做到這一點的最佳方法是什么?

圓角還是整圓? 無論如何,假設您想要第二個選項,您應該將故事板上的縱橫比(寬度:高度)限制為 1:1,以便標簽始終為正方形。 然后,在代碼中,您可以執行以下操作

pResult.layer.cornerRadius = pResult.frame.width/2

無論屏幕大小如何,始終使它成為一個完美的圓圈。

如果您想制作完美的圓形,請首先確保您的標簽寬度和高度相同。

pResult.layer.cornerRadius = CGRectGetWidth(pResult.frame)/2
pResult.layer.masksToBounds = true

參考

如果您使用的是 swift 3,請嘗試以下操作:

lblRoundDot.layer.cornerRadius = lblRoundDot.frame.width/2
lblRoundDot.layer.masksToBounds = true

基於上一個答案,但這個答案在 Swift 4.2 中:

    label.layer.cornerRadius =  label.frame.width/2
    label.layer.masksToBounds = true
//You can provide UserdefiendRunTimeConstraints on the Label using Storyboard or XIB  Select label and give 

(例如,您的標簽寬度 = 100 和高度 = 100)

 KeyPath =layer.cornerRadius
 Type = Number
 Value = 50

 KeyPath = layer.masksToBounds
 Type = Boolean
 Value = True

 KeyPath = layer.borderWidth
 Type = Number
 Value = 2

取決於@FruitAddict 的回答,我想把它改進得更完美。 您應該使用 .height 屬性而不是 .width 原因,以防標簽的長度更長(文本增加)此代碼將不起作用。 代碼將是這樣的:

pResult.layer.cornerRadius = pResult.frame.height / 2

創建 UILabel 擴展

extension UILabel {
    func addBadge(badgeCount: String) {
       self.text = badgeCount
        self.textColor = UIColor.white
        self.textAlignment = .center
        self.font = UIFont.systemFont(ofSize: 14.0)
       self.layer.cornerRadius = 0.5 * self.bounds.size.width
        self.layer.backgroundColor = UIColor.orange.cgColor
       
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM