【发布时间】:2016-05-31 19:41:09
【问题描述】:
我的问题很简单。在android中,我们可以将xml样式表从布局中分离出来,这样它就可以在任何地方重复使用,并且可以很容易地进行UI设计更改。
iOS xcode 中也可以吗?如果可以如何(如果不是来自控制器,则更喜欢)?需要图书馆吗?什么是好的图书馆?
感谢您的回答。
【问题讨论】:
-
子类化 UI 组件?
-
您可以为此目的使用类别类。
我的问题很简单。在android中,我们可以将xml样式表从布局中分离出来,这样它就可以在任何地方重复使用,并且可以很容易地进行UI设计更改。
iOS xcode 中也可以吗?如果可以如何(如果不是来自控制器,则更喜欢)?需要图书馆吗?什么是好的图书馆?
感谢您的回答。
【问题讨论】:
您可以使用枚举创建自己的样式。通过将枚举放在 Styles 枚举中,您可以获得一个很好的分组:
enum Styles {
enum Labels {
case Standard
case LargeText
func style(label: UILabel) {
switch self {
case .Standard:
label.font = UIFont.systemFontOfSize(12)
case .LargeText:
label.font = UIFont.systemFontOfSize(18)
}
}
}
enum Buttons {
case RedButton
func style(button: UIButton) {
switch self {
case .RedButton:
button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
}
}
}
}
那么你可以这样使用它:
Styles.Labels.Standard.style(yourLabel)
您还可以为您设置的样式进行扩展:
extension UILabel {
func style(style: Styles.Labels) {
style.style(self)
}
}
extension UIButton {
func style(style: Styles.Buttons) {
style.style(self)
}
}
然后像这样使用扩展:
yourLabel.style(.Standard)
yourButton.style(.RedButton)
【讨论】:
您还应该查看UIAppearance。它是一种设计代理,可用于您只需设置一次样式的大多数 UI 元素。
【讨论】:
您可以为此目的使用 UIView 的 UICategory 类。为设置borders、border colors、通过bazier-paths、cornerradius 等创建不同的方法。这只是其中的几个。类别是 UIView 所以你可以在buttons,lables,textview,textedits等上使用;
UIView+category.h
@interface UIView (category)
-(void)makeToRoundEdgeWithBorder:(CGFloat )borderwidth bordecolor:(UIColor *)color;
@end
UIView+category.m
@implementation UIView (category)
-(void)makeToRoundEdgeWithBorder:(CGFloat )borderwidth bordecolor:(UIColor *)color
{
NSLog(@"height %f width %f",CGRectGetHeight(self.frame),CGRectGetWidth(self.frame));
self.layer.cornerRadius=CGRectGetHeight(self.frame)/2;
self.layer.masksToBounds=YES;
self.layer.borderColor=[color CGColor];
self.layer.borderWidth=borderwidth;
}
@end
使用它
[yourlable makeToRoundEdgeWithBorder:0.0f bordercolor:[UIColor clearColor] cornerRadius:8.0f];
[yourbutton makeToRoundEdgeWithBorder:0.0f bordercolor:[UIColor clearColor] cornerRadius:8.0f];
[yourTextview makeToRoundEdgeWithBorder:0.0f bordercolor:[UIColor clearColor] cornerRadius:8.0f];
[yourTextfield makeToRoundEdgeWithBorder:0.0f bordercolor:[UIColor clearColor] cornerRadius:8.0f];
【讨论】:
UICategory 这样的东西。类别只是向现有类添加新功能的一种方式。
【讨论】:
NOTICE: Classy is no longer actively maintained see: Looking for contributors,因此可能不是一个好的选择。