UILabelのサイズを動的に調整する方法
ラベル表示する時にサイズを動的に調整させたい場合があるかも?
そのやり方を書きたいと思います。
結構面倒いので...。
NSStringからCGSizeを取ってくるやり方になります。
CGSizeを取るには、フォントと改行モードと最大サイズの情報が必要です。
インターフェイスの定義です。
@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *label; @end
それで、実装部分は、メソッドにしました。
- (CGSize)generateCGSize:(NSString *)str { // 最大サイズ CGSize maxSize = CGSizeMake(100, 500); // 改行モード UILineBreakMode breakMode = UILineBreakModeWordWrap; // フォント UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:14]; // CGSizeを戻します。 return [str sizeWithFont:font constrainedToSize:maxSize lineBreakMode:breakMode]; }
あとは、viewDidLoadメソッド内にCGSizeを設定する部分を実装するだけです。
サイズを設定するのは、UILabelのframeにCGRectMakeを使って設定します。
@implementation ViewController @synthesize label; - (void)viewDidLoad { [super viewDidLoad]; // 文字列設定 NSString *str = @"こんにちは"; // 画面センター位置取得 int width = [[UIScreen mainScreen]applicationFrame].size.width; int height = [[UIScreen mainScreen]applicationFrame].size.height; // XY軸,表示文字の高さ幅設定 label.frame = CGRectMake((width/2)-(size.width/2), height/2, size.width, size.height); // サイズ取得 CGSize size = [self generateCGSize:str]; // サイズ設定 label.frame = CGRectMake(0, 0, size.width, size.height); // 文字列設定 label.text = str; // 文字カラー設定 label.textColor = [UIColor purpleColor]; // バックグラウンドカラー設定 label.backgroundColor = [UIColor whiteColor]; } ....
最後に〜.storyboardは、こんな感じです。
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="1.1" toolsVersion="2182" systemVersion="11E53" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="3"> <scenes> <!--View Controller--> <scene sceneID="1"> <objects> <placeholder id="2" placeholderIdentifier="IBFirstResponder" sceneMemberID="firstResponder"/> <viewController id="3" customClass="ViewController" sceneMemberID="viewController"> <view key="view" contentMode="scaleToFill" id="3-1"> <rect key="frame" x="0.0" y="20" width="320" height="460"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <subviews> <label id="3-2"> </label> </subviews> <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/> </view> <connections> <outlet id="3-3" property="myLabel" destination="3-2"/> </connections> </viewController> </objects> </scene> </scenes> <simulatedMetricsContainer key="defaultSimulatedMetrics"> <simulatedStatusBarMetrics key="statusBar"/> <simulatedOrientationMetrics key="orientation"/> <simulatedScreenMetrics key="destination"/> </simulatedMetricsContainer> </document>