我已經創建了一個自定義視圖(從UIView派生的新類)。此視圖旨在用作我的iOS應用程序中的標題,基本上包含兩個名爲「Title」和「SubTitle」的標籤。我創建了兩個匹配的字符串屬性,可用於設置「標題」和「子標題」標籤的文本。Xamarin iOS自定義視圖
我的問題是,什麼是最好的地方分配提供給屬性的字符串值(假設使用綁定MvvmCross或只是簡單的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());
}
}
對不起,最近的反應,並感謝您的答覆。然而,我的問題更多的是關於自定義視圖的內部(因爲這應該是一個可重用的控制/視圖)。主要是如果自定義視圖本身的'Draw'方法是設置文本屬性的正確位置。從外面我肯定會使用MvvmCross綁定到控件。我問的原因是,我覺得'Draw'方法更適合真正做圖形(但這真的只是一種感覺)。 –
好吧,比簡單地實現像這樣的屬性:'公共字符串SubTitle {得到{返回_subTitle.Text; } set {_subTitle.Text = value; }}' –
當值更改時,這也會自動更新視圖嗎? –