【问题标题】:Limit and scale the size of text in UITextField限制和缩放 UITextField 中的文本大小
【发布时间】:2017-06-20 05:29:58
【问题描述】:

我有一个UITextField 和两个CAShapeLayers。我想让我的文本始终居中并且(大小)限制在内部的白色圆圈内。

我怎样才能限制该白色圆圈内的文本大小,最好使用填充,但还要使文本始终填充该空间?第二部分问题与缩放因子有关,如果有更多文本,它会将文本字体大小设置得更小。

这是我的 MWE:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .darkGray

        let size:CGFloat = 300.0
        let centerPoint:CGFloat = 200.0

        let valueLabel = UITextField()
        valueLabel.isUserInteractionEnabled = false
        valueLabel.contentVerticalAlignment = .center
        valueLabel.textAlignment = .center
        valueLabel.text = "300"
        valueLabel.textColor = .black

        valueLabel.font = UIFont.init(name: "HelveticaNeue-Medium", size: 100)
        valueLabel.bounds = CGRect(x:0.0, y:0.0, width:size, height:size)
        valueLabel.center = CGPoint(x:centerPoint, y:centerPoint)

        let redCircle:CAShapeLayer = CAShapeLayer()
        redCircle.path = UIBezierPath(ovalIn: valueLabel.bounds).cgPath
        redCircle.fillColor = UIColor.red.cgColor
        redCircle.strokeColor = UIColor.white.cgColor
        redCircle.lineWidth = 10

        valueLabel.layer.addSublayer(redCircle)

        let whiteCircle:CAShapeLayer = CAShapeLayer()
        let tmpRect = CGRect(x:valueLabel.bounds.origin.x,y:valueLabel.bounds.origin.x,width:valueLabel.bounds.width-80.0,height:valueLabel.bounds.height-80.0)
        whiteCircle.path = UIBezierPath(ovalIn: tmpRect).cgPath
        whiteCircle.fillColor = UIColor.white.cgColor
        whiteCircle.strokeColor = UIColor.white.cgColor
        whiteCircle.lineWidth = 10
        let posX = valueLabel.bounds.midX - (size-80.0)/2.0
        let posY = valueLabel.bounds.midY - (size-80.0)/2.0
        whiteCircle.position = CGPoint(x:posX, y:posY)
        valueLabel.layer.addSublayer(whiteCircle)

        self.view.addSubview(valueLabel)
    }
}

【问题讨论】:

    标签: ios swift uitextfield centering cashapelayer


    【解决方案1】:

    为此,我建议使用 UITextView,它通过 NSTextContainer 提供了对它的原生支持。 docs

    textView.textContainer.exclusionPaths = [..] // array of UIBezierPaths
    

    【讨论】:

      【解决方案2】:

      你可以试试

      valueLabel.adjustsFontSizeToFitWidth = true
      valueLabel.minimumFontSize = 0.5
      

      希望对你有用。

      【讨论】:

      • minimumFontSize 已弃用 iOS 7
      • 顺便说一句,要设置最小字体大小的限制,您需要设置要应用于字体大小的最小比例,设置 minimumScaleFactor 属性 iOS 7+
      猜你喜欢
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      相关资源
      最近更新 更多