【问题标题】:Aligning UILabel and UIImage对齐 UILabel 和 UIImage
【发布时间】:2015-06-28 22:57:20
【问题描述】:

我正在使用 Xamarin.iOS,我希望 UILabel 和 UIImage 与容器视图的相同边距对齐。见下图

现在,图像和文本具有相同的高度,但由于标签的填充,顶部和底部的边距更大。顺便说一句,我已经使用了 SizeToFit()。 这是我的代码:

nfloat gap = 10f;
UIView containerView = new UIView ();
UILabel textView = new UILabel ();
textView.BackgroundColor = UIColor.Red;
textView.Text = "HELLO!";
textView.Font = UIFont.FromName ("Arial-BoldMT", 40f);
textView.ContentMode = UIViewContentMode.Bottom;
textView.SizeToFit ();
textView.Frame = new CGRect (gap, gap, textView.Frame.Width, textView.Frame.Height);
containerView.AddSubview (textView);

UIImageView imgView = new UIImageView (UIImage.FromBundle ("Sample-icon"));
imgView.Frame = new CGRect (textView.Frame.X + textView.Frame.Width + gap,
textView.Frame.Y, textView.Frame.Height, textView.Frame.Height);
imgView.ContentMode = UIViewContentMode.ScaleToFill;
containerView.AddSubview (imgView);

containerView.Frame = new CGRect(10, 50, gap + textView.Frame.Width + gap + imgView.Frame.Width + gap, gap + textView.Frame.Height + gap);
containerView.BackgroundColor = UIColor.Yellow;
View.AddSubview (containerView);

现在的样子:

我的问题是如何删除所有填充(包括顶部和底部),如果仍然可以,我可以删除左右的小填充

我能看懂 Objective-C 代码,所以如果有使用它的参考,请分享

谢谢!

更新! 这是我的 CustomLabel,结果相同。

【问题讨论】:

    标签: c# ios xamarin


    【解决方案1】:

    试试这个link

    为所有插入设置 0。所以你不会得到额外的填充

    CustomLabel.h

     #import <UIKit/UIKit.h>
    
     @interface CustomLabel : UILabel
    
     @end
    

    CustomLabel.m

    #import "CustomLabel.h"
    #import <QuartzCore/QuartzCore.h>
    
    @implementation CustomLabel
    
    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code
        }
        return self;
    }
    
    // for inset
    -(void) drawTextInRect:(CGRect)rect
    {
        UIEdgeInsets insets = {0, 0, 0, 0};
    
        [super drawTextInRect: UIEdgeInsetsInsetRect(rect, insets)];    
    }
    

    YourViewController.h

    #import <UIKit/UIKit.h>
    #import "CustomLabel.h"
    
    @interface YourViewController : UIViewController {
        CustomLabel *myLabel;
    }
    
    @property (strong, nonatomic) IBOutlet CustomLabel *textView;
    
    @end
    

    【讨论】:

    • 嗨@Sujay,我试过了。我已经尝试对 UILabel 进行子类化,但它不起作用。
    • @marsh08,您是否在文本字段中使用了自定义类名?
    • 你是不是有点像这样:textView = new CustomButtonLabel();..?是的
    • 您已使用以下代码创建标签 UILabel textView = new UILabel(); 而不是使用 UILabel 使用您为子类化 UILabel 创建的自定义类名称尝试 CustomLabel textView = new CustomLabel();
    • 对不起,上面的那个不是我真正使用的那个,而是相同的实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多