How to set top-left alignment for UILabel for iOS application?

后端 未结 21 1453
傲寒
傲寒 2020-12-04 07:54

I have added one label in my nib file, then its required to have top-left alignment for that lable. As I am providing text at runtime so its not sure that how much lines the

21条回答
  •  北海茫月
    2020-12-04 08:29

    Solution with SoLabel works , Thanks.

    Bellow I have added monotouch version:

        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
    }
    

提交回复
热议问题