【发布时间】:2016-02-23 10:37:14
【问题描述】:
我创建了一个自定义视图(从 UIView 派生的新类)。此视图旨在用作我的 iOS 应用程序中的标题,并且基本上包含两个标签,称为“标题”和“子标题”。我创建了两个匹配的字符串属性,可用于设置“标题”和“子标题”标签的文本。
我的问题是,将提供给属性的字符串值分配给标签的 .text 属性的最佳位置是什么?
我知道当我覆盖Draw(CGRect rect) 方法并在此处分配值时它会起作用(并在属性值更改时调用SetNeedsDisplay() 方法)。然而,打电话给Draw(CGRect rect) 对我来说是错误的。任何帮助将不胜感激。
目前我有以下代码:
[Register("MenuHeaderView"), DesignTimeVisible(true)]
public class MenuHeaderView : UIView
{
private const int _margin = 5;
private UILabel _title;
private UILabel _subTitle;
public MenuHeaderView()
{
Initialize();
}
public MenuHeaderView(CGRect frame)
: base(frame)
{
Initialize();
}
public MenuHeaderView(IntPtr p)
: base(p)
{
Initialize();
}
[Export("Title"), Browsable(true)]
public string Title { get; set; }
[Export("SubTitle"), Browsable(true)]
public string SubTitle { get; set; }
private void Initialize()
{
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
// Create 'Title' label
_title = new UILabel()
{
BackgroundColor = UIColor.Clear,
Font = UIFont.BoldSystemFontOfSize(UIFont.SystemFontSize),
TextAlignment = UITextAlignment.Left,
TextColor = UIColor.White,
Text = "Verbeterapp",
TranslatesAutoresizingMaskIntoConstraints = false
};
// Create 'SubTitle' label
_subTitle = new UILabel()
{
BackgroundColor = UIColor.Clear,
Font = UIFont.SystemFontOfSize(UIFont.SystemFontSize),
TextAlignment = UITextAlignment.Left,
TextColor = UIColor.White,
Text = "JCI",
TranslatesAutoresizingMaskIntoConstraints = false
};
this.AddSubviews(new UIView[] { _title, _subTitle });
SetNeedsUpdateConstraints();
}
public override void UpdateConstraints()
{
if (NeedsUpdateConstraints())
SetupContraints();
base.UpdateConstraints();
}
private void SetupContraints()
{
var constraints = new List<NSLayoutConstraint>();
var viewMetrics = new Object[] {
"titleLabel", _title,
"subTitleLabel", _subTitle,
"margin", _margin
};
constraints.AddRange(
NSLayoutConstraint.FromVisualFormat(
"V:[titleLabel]-margin-[subTitleLabel]",
NSLayoutFormatOptions.AlignAllLeading,
viewMetrics
)
);
constraints.Add(
NSLayoutConstraint.Create (
_title,
NSLayoutAttribute.Left,
NSLayoutRelation.Equal,
this,
NSLayoutAttribute.Left,
1,
8
)
);
constraints.Add (
NSLayoutConstraint.Create(
_title,
NSLayoutAttribute.CenterY,
NSLayoutRelation.Equal,
this,
NSLayoutAttribute.CenterY,
1,
-_subTitle.Frame.Height
)
);
AddConstraints(constraints.ToArray());
}
}
【问题讨论】: