Iphone 如何为iOS应用程序的UILabel设置左上对齐?
我已经在我的nib文件中添加了一个标签,然后需要对该标签进行左上对齐。因为我在运行时提供文本,所以不确定有多少行。 所以,如果文本只包含一行,则显示为垂直居中对齐。该对齐方式与它前面的相应标签不匹配 例如: 这看起来很奇怪:(Iphone 如何为iOS应用程序的UILabel设置左上对齐?,iphone,ios,label,uilabel,text-alignment,Iphone,Ios,Label,Uilabel,Text Alignment,我已经在我的nib文件中添加了一个标签,然后需要对该标签进行左上对齐。因为我在运行时提供文本,所以不确定有多少行。 所以,如果文本只包含一行,则显示为垂直居中对齐。该对齐方式与它前面的相应标签不匹配 例如: 这看起来很奇怪:( 有什么方法可以将标签文本正确设置为左上对齐吗?我将链接到这个内容广泛且评分较高的问题/答案,而不是重新解释: 简而言之,答案是否定的,苹果并没有让这变得容易,但可以通过改变帧大小来实现。这相当容易。使用verticalAlignment属性创建一个UILabel子容器
有什么方法可以将标签文本正确设置为左上对齐吗?我将链接到这个内容广泛且评分较高的问题/答案,而不是重新解释:
简而言之,答案是否定的,苹果并没有让这变得容易,但可以通过改变帧大小来实现。这相当容易。使用
verticalAlignment
属性创建一个UILabel
子容器,并覆盖textRectForBounds:limitedToNumberOfLines
以返回顶部、中部或底部垂直的正确边界al校准。以下是代码:
SOLabel.h
#import <UIKit/UIKit.h>
typedef enum
{
VerticalAlignmentTop = 0, // default
VerticalAlignmentMiddle,
VerticalAlignmentBottom,
} VerticalAlignment;
@interface SOLabel : UILabel
@property (nonatomic, readwrite) VerticalAlignment verticalAlignment;
@end
在代码中
label.text = @"some text";
[label sizeToFit];
请注意,如果在使用不同数据回收的表格单元格或其他视图中使用该框架,则需要将原始框架存储在某个位置,并在调用sizeToFit之前将其重置。我也遇到了此问题,但我发现设置UILabel属性和方法的顺序很重要 如果在
label.font=[UIFont fontWithName:@“Helvetica”size:14];
之前调用[label size-to-fit]
,则文本不会与顶部对齐,但如果将它们互换,则会对齐
我还注意到,首先设置文本也会产生影响
希望这有帮助。SoLabel works解决方案,谢谢 下面我添加了monotouch版本:
public class UICustomLabel : UILabel
{
private UITextVerticalAlignment _textVerticalAlignment;
public UICustomLabel()
{
TextVerticalAlignment = UITextVerticalAlignment.Top;
}
public UITextVerticalAlignment TextVerticalAlignment
{
get
{
return _textVerticalAlignment;
}
set
{
_textVerticalAlignment = value;
SetNeedsDisplay();
}
}
public override void DrawText(RectangleF rect)
{
var bound = TextRectForBounds(rect, Lines);
base.DrawText(bound);
}
public override RectangleF TextRectForBounds(RectangleF bounds, int numberOfLines)
{
var rect = base.TextRectForBounds(bounds, numberOfLines);
RectangleF resultRect;
switch (TextVerticalAlignment)
{
case UITextVerticalAlignment.Top:
resultRect = new RectangleF(bounds.X, bounds.Y, rect.Size.Width, rect.Size.Height);
break;
case UITextVerticalAlignment.Middle:
resultRect = new RectangleF(bounds.X,
bounds.Y + (bounds.Size.Height - rect.Size.Height)/2,
rect.Size.Width, rect.Size.Height);
break;
case UITextVerticalAlignment.Bottom:
resultRect = new RectangleF(bounds.X,
bounds.Y + (bounds.Size.Height - rect.Size.Height),
rect.Size.Width, rect.Size.Height);
break;
default:
resultRect = bounds;
break;
}
return resultRect;
}
}
public enum UITextVerticalAlignment
{
Top = 0, // default
Middle,
Bottom
}
SOLabel对我有用 Swift 3和5: 此版本已从原始版本更新,以支持RTL语言:
public class VerticalAlignLabel: UILabel {
enum VerticalAlignment {
case top
case middle
case bottom
}
var verticalAlignment : VerticalAlignment = .top {
didSet {
setNeedsDisplay()
}
}
override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)
if UIView.userInterfaceLayoutDirection(for: .unspecified) == .rightToLeft {
switch verticalAlignment {
case .top:
return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
case .middle:
return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
case .bottom:
return CGRect(x: self.bounds.size.width - rect.size.width, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
}
} else {
switch verticalAlignment {
case .top:
return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
case .middle:
return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
case .bottom:
return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
}
}
}
override public func drawText(in rect: CGRect) {
let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
super.drawText(in: r)
}
}
Swift 1:
使用interface builder时,请设置标签的约束条件(确保同时设置高度和宽度)。然后在“大小检查器”中检查标签的高度。您希望标签的读数为>=而不是=。然后在该视图控制器的实现中,将行数设置为0(也可以在IB中完成)然后设置标签[label sizeToFit];随着文本长度的增加,标签的高度会增加,并将文本保持在左上角。我找到了解决相同问题的另一种方法。我使用了
UITextView
而不是UILabel
并切换了editable()
函数设置为false
对于iOS 7,这就是我为自己制作和工作的
@implementation UILabel (VerticalAlign)
- (void)alignTop
{
CGSize boundingRectSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
NSDictionary *attributes = @{NSFontAttributeName : self.font};
CGRect labelSize = [self.text boundingRectWithSize:boundingRectSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
int numberOfLines= ceil(labelSize.size.height / self.font.lineHeight);
CGRect newFrame = self.frame;
newFrame.size.height = numberOfLines * self.font.lineHeight;
self.frame = newFrame;
}
- (void)alignBottom
{
CGSize boundingRectSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
NSDictionary *attributes = @{NSFontAttributeName : self.font};
CGRect labelSize = [self.text boundingRectWithSize:boundingRectSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
int numberOfLines= ceil(labelSize.size.height / self.font.lineHeight);
int numberOfNewLined = (self.frame.size.height/self.font.lineHeight) - numberOfLines;
NSMutableString *newLines = [NSMutableString string];
for(int i=0; i< numberOfNewLined; i++){
[newLines appendString:@"\n"];
}
[newLines appendString:self.text];
self.text = [newLines mutableCopy];
}
@实现UILabel(垂直对齐)
-(空)对齐顶部
{
CGSize boundingRectSize=CGSizeMake(self.frame.size.width,CGFLOAT_MAX);
NSDictionary*attributes=@{NSFontAttributeName:self.font};
CGRect labelSize=[self.text boundingRectWithSize:boundingRectSize选项:NSStringDrawingUserLineFragmentOrigin | NSStringDrawingUserFontLeading
属性:属性
上下文:无];
int numberOfLines=ceil(labelSize.size.height/self.font.lineHeight);
CGRect newFrame=self.frame;
newFrame.size.height=numberOfLines*self.font.lineHeight;
self.frame=newFrame;
}
-(空)对齐底部
{
CGSize boundingRectSize=CGSizeMake(self.frame.size.width,CGFLOAT_MAX);
NSDictionary*attributes=@{NSFontAttributeName:self.font};
CGRect labelSize=[self.text boundingRectWithSize:boundingRectSize选项:NSStringDrawingUserLineFragmentOrigin | NSStringDrawingUserFontLeading
属性:属性
上下文:无];
int numberOfLines=ceil(labelSize.size.height/self.font.lineHeight);
int numberOfNewLined=(self.frame.size.height/self.font.lineHeight)-numberOfLines;
NSMutableString*换行符=[NSMutableString];
for(int i=0;i
Swift 2.0::使用UILabel扩展
在空Swift文件中设置常量枚举值
// AppRef.swift
import UIKit
import Foundation
enum UILabelTextPositions : String {
case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"
}
使用UILabel扩展:
创建一个空的Swift类并命名它
// AppExtensions.swift
import Foundation
import UIKit
extension UILabel{
func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
{
let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)
switch positionIdentifier
{
case "VerticalAlignmentTop":
sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
break;
case "VerticalAlignmentMiddle":
sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
rect.size.width, rect.size.height);
break;
case "VerticalAlignmentBottom":
sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
break;
default:
sampleLabel!.frame = bounds;
break;
}
return sampleLabel!
}
}
用法:
myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)
我在故事板中找到了使用自动布局的解决方案 1) 将行数设置为0,文本对齐设置为左侧 2) 设置高度约束 3) 高度约束应该是相对的-小于或等于 (四) 我得到的结果如下:
Swift 3版@totiG的答案
class UIVerticalAlignLabel: UILabel {
enum VerticalAlignment : Int {
case VerticalAlignmentTop = 0
case VerticalAlignmentMiddle = 1
case VerticalAlignmentBottom = 2
}
@IBInspectable var verticalAlignment : VerticalAlignment = .VerticalAlignmentTop {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)
switch(verticalAlignment) {
case .VerticalAlignmentTop:
return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
case .VerticalAlignmentMiddle:
return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
case .VerticalAlignmentBottom:
return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
}
}
override func drawText(in rect: CGRect) {
let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
super.drawText(in: r)
}
}
最简单、最简单的方法是将标签嵌入StackView,并在序列图像板的属性检查器中将StackView的轴设置为水平,与顶部对齐。如果您需要的是默认从左上角开始的不可编辑文本,您只需使用文本视图而不是标签,然后将其状态设置为不可编辑,像这样:
textview.isEditable = false
比搞乱标签容易多了
干杯 在totiG令人敬畏的答案的基础上,我创建了一个IBDesignable类,可以非常轻松地从故事板定制UILabel的垂直对齐方式。只需确保从情节提要标识检查器将UILabel的类设置为“VerticalAlignLabel”。如果垂直对齐没有生效,请转到编辑器->刷新所有视图,这应该会起作用 工作原理: 正确设置UILabel的类后,序列图像板应显示一个接受整数(对齐代码)的输入字段 更新:我添加了对居中标签~Sev的支持
输入0作为“顶部对齐” 输入1作为中间对齐 输入2作为“底部对齐”
@IBDesignable类垂直排列
override func viewWillLayoutSubviews() {
sampleLabel.sizeToFit()
}
class UIVerticalAlignLabel: UILabel {
enum VerticalAlignment : Int {
case VerticalAlignmentTop = 0
case VerticalAlignmentMiddle = 1
case VerticalAlignmentBottom = 2
}
@IBInspectable var verticalAlignment : VerticalAlignment = .VerticalAlignmentTop {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines: Int) -> CGRect {
let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: limitedToNumberOfLines)
switch(verticalAlignment) {
case .VerticalAlignmentTop:
return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: rect.size.width, height: rect.size.height)
case .VerticalAlignmentMiddle:
return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height) / 2, width: rect.size.width, height: rect.size.height)
case .VerticalAlignmentBottom:
return CGRect(x: bounds.origin.x, y: bounds.origin.y + (bounds.size.height - rect.size.height), width: rect.size.width, height: rect.size.height)
}
}
override func drawText(in rect: CGRect) {
let r = self.textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
super.drawText(in: r)
}
}
textview.isEditable = false
override func layoutSubViews() {
super.layoutSubViews()
// Do other works if needed
label.sizeToFit()
}
titleLabel.frame = CGRect(x: 20, y: 20, width: 374, height: 291.2)
titleLabel.backgroundColor = UIColor.clear //set a light color to see the frame
titleLabel.textAlignment = .left
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.numberOfLines = 4
titleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 35)
titleLabel.text = "Example"
titleLabel.sizeToFit()
self.view.addSubview(titleLabel)
final class TestVC: UIViewController {
lazy var testTextLabel: UITextView = {
$0.isScrollEnabled = false
$0.isEditable = false
$0.font = .systemFont(ofSize: 17, weight: .medium)
$0.textColor = .black
$0.layer.borderWidth = 1
$0.layer.borderColor = UIColor.black.cgColor
$0.layer.cornerRadius = 5
return $0
}(UITextView())
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
testTextLabel.text = "Your text"
view.addSubview(testTextLabel)
testTextLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
testTextLabel.topAnchor.constraint(equalTo: testTextLabel.superview!.safeAreaLayoutGuide.topAnchor, constant: 12),
testTextLabel.leadingAnchor.constraint(equalTo: testTextLabel.superview!.leadingAnchor, constant: 12),
testTextLabel.widthAnchor.constraint(equalToConstant: 250),
testTextLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 70)
])
}
}