有没有办法确定adjustsFontSizeToFitWidth是否已触发?

时间:2015-02-26 21:23:24

标签: swift ios8 xcode6 uilabel

无论如何确定是否已触发adjustsFontSizeToFitWidth?我的应用程序有一个占用整个视图的UILabel。通过使用UIPinchGestureRecognizer,您可以捏合和缩小以更改字体大小。效果很好。但是,当字体达到UILabel的最大大小时,它会显示奇怪的行为。 UILabel中的文字向下移动到UILabel。如果不添加bannerLabel.adjustsFontSizeToFitWidth = true,文字会被剪裁。我想知道当字体达到UILabel的最大大小时,我将不再尝试增加字体大小。

import UIKit

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var bannerLabel: UILabel!

    var perviousScale:CGFloat = 0
    var fontSize:CGFloat          = 0
    var originalFontSize: CGFloat = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let pinchGesture = UIPinchGestureRecognizer(target: self, action: Selector("pinch:"))
        view.addGestureRecognizer(pinchGesture)
        perviousScale = pinchGesture.scale

        bannerLabel.adjustsFontSizeToFitWidth = true

        originalFontSize = bannerLabel.font.pointSize
        fontSize         = originalFontSize

    }

    func pinch(sender:UIPinchGestureRecognizer) {

        println("font size \(bannerLabel.font.pointSize)")

        if perviousScale >= sender.scale  //Zoom In
        {
            decreaseFontSize()

        }
        else if perviousScale < sender.scale  //Zoom Out
        {
            increaseFontSize()
        }

    }

    func threeFingers(sender:UIPanGestureRecognizer) {

        println("threeFingers")

    }

    override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {

        bannerLabel.font = UIFont(name: bannerLabel.font.fontName, size: fontSize)

    }

    func increaseFontSize(){

        bannerLabel.font = UIFont(name: bannerLabel.font.fontName, size: fontSize)

        fontSize = fontSize + 2.5

    }

    func decreaseFontSize(){

        bannerLabel.font = UIFont(name: bannerLabel.font.fontName, size: fontSize)

        if fontSize >= originalFontSize {

            fontSize = fontSize - 2.5
        }
    }
}

1 个答案:

答案 0 :(得分:0)

是的,您可以添加观察者:

1)将动态修改器添加到您要观察的属性中:

dynamic UILabel bannerLabel = UILabel()

2)创建全局上下文变量

private var myContext = 0

3)添加关键路径的观察者

bannerLabel.addObserver(self, forKeyPath: "adjustsFontSizeToFitWidth", options:.New, context:&myContext)    

4)覆盖observeValueForKeyPath并删除deinit中的观察者

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) {
        if context == &myContext {
            println("Font size adjusted to fit width: \(change[NSKeyValueChangeNewKey])")
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }

 deinit {
        bannerLabel .removeObserver(self, forKeyPath: "adjustsFontSizeToFitWidth", context: &myContext)
    }