How to set a label's preferredMaxLayoutWidth to automatic programmatically?

前端 未结 1 1047
轻奢々
轻奢々 2021-02-13 03:34

I get the following errors when I attempt to set a label\'s Preferred Width to Automatic in a storyboard:

Attribute Unav

1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 03:56

    I haven't figured out a way to do this programmatically, but there is a pretty decent workaround.

    Any valid workaround must meet these requirements:

    • Use automatic preferredMaxLayoutWidth on iOS 8, and explicit on iOS 7.
    • Must not have warnings.

    The only way to set preferredMaxLayoutWidth to automatic is via a storyboard, so we do so.

    In order to suppress the above warning, set the number of Lines to 1.

    Now, programmatically, do the following:

    self.label.numberOfLines = 0;
    if (iOS8) {
        ; // do nothing, it will use automatic via the storyboard
    } else {
        self.label.preferredMaxLayoutWidth = screenWidth - 32;
    }
    

    For reference, here is how to find out the iOS version, and here is how to get the screen width. Note that you must specifically look for iOS 8 and not whether or not the object responds to preferredMaxLayoutWidth, since that property was added in iOS 6.

    0 讨论(0)
提交回复
热议问题